Flores
Flores

Reputation: 8942

Auto inject javascript in blazor application

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?

Upvotes: 5

Views: 2461

Answers (1)

Flores
Flores

Reputation: 8942

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>

Upvotes: 9

Related Questions