Auto inject javascript in blazor application

asp.net-core blazor c#

Question

I'm developing a Blazor extension library.

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>

and this in my code:

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

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)

Any ideas on this?

Accepted Answer

Edit

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 answer

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

And adding it to my app.cshtml like this:

@addTagHelper *, BlazorExtensions

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

<BlazorExtensionScripts></BlazorExtensionScripts>



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why