在blazor应用程序中自动注入javascript

Flo*_*res 4 c# asp.net-core blazor

我正在开发一个Blazor扩展库.

这个库中的一件事是重用javascript alert()方法.我知道如何做到这一点,这涉及在.cshtml页面中添加:

<script>
  Blazor.registerFunction('Alert', (message) => {
      alert(message);
  });
</script>
Run Code Online (Sandbox Code Playgroud)

这在我的代码中:

public void Alert(string message)
{
     RegisteredFunction.Invoke<object>("Alert", message);
}
Run Code Online (Sandbox Code Playgroud)

如果你使用我的包(或者可能总是),我想以某种方式将javascript部分自动注入html中.不确定这是否可行(还)

有什么想法吗?

Flo*_*res 8

编辑

由于blazor 0.2有一个更受支持的方式来做到这一点.查看blazorlib模板的示例:

dotnet new -i Microsoft.AspNetCore.Blazor.Templates

dotnet new blazorlib

0.1回答

我最终创建了自己的包含我的javascript的blazor组件,如下所示:

public class BlazorExtensionScripts : Microsoft.AspNetCore.Blazor.Components.BlazorComponent
{

    protected override void BuildRenderTree(Microsoft.AspNetCore.Blazor.RenderTree.RenderTreeBuilder builder)
    {
        builder.OpenElement(0, "script");
        builder.AddContent(1, "Blazor.registerFunction('Alert', (message) => { alert(message); });");
        builder.CloseElement();
    }
}
Run Code Online (Sandbox Code Playgroud)

并将其添加到我的app.cshtml中,如下所示:

@addTagHelper *, BlazorExtensions

<Router AppAssembly=typeof(Program).Assembly />

<BlazorExtensionScripts></BlazorExtensionScripts>
Run Code Online (Sandbox Code Playgroud)

  • 这是因为我的组件存在于另一个组件中.这是一个解决方法:https://github.com/aspnet/Blazor/issues/394 (2认同)