在blazor应用程序中自动注入javascript [英] Auto inject javascript in blazor application

查看:394
本文介绍了在blazor应用程序中自动注入javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发Blazor扩展库.

I'm developing a Blazor extension library.

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

One thing in this library would be the reuse of the javascript alert() method. I know how to do this, this involves adding this in a .cshtml page:

<script>
  Blazor.registerFunction('Alert', (message) => {
      alert(message);
  });
</script>

这在我的代码中:

public void Alert(string message)
{
     RegisteredFunction.Invoke<object>("Alert", message);
}

如果您使用我的软件包(或始终使用),我希望将javascript部分以某种方式自动注入html中.不确定是否可行

I would like the javascript part somehow to be auto injected in the html if you use my package (or maybe always). Not sure if this is possible (yet)

对此有何想法?

推荐答案

编辑

自blazor 0.2起,有一种更受支持的方式来执行此操作.以blazorlib模板为例:

Since blazor 0.2 there is a more supported way to do this. Look at the blazorlib template for an example:

dotnet new -i Microsoft.AspNetCore.Blazor.Templates

dotnet new blazorlib

0.1个答案

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

I ended up with creating my own blazor component containing my javascript, like this:

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();
    }
}

像这样将其添加到我的app.cshtml中:

And adding it to my app.cshtml like this:

@addTagHelper *, BlazorExtensions

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

<BlazorExtensionScripts></BlazorExtensionScripts>

这篇关于在blazor应用程序中自动注入javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆