Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 712
Flores Avatar asked Mar 27 '18 07:03

Flores


People also ask

How do I add JavaScript to Blazor app?

Integrating JavaScript and Blazor is a little awkward because you can't add JavaScript to a Blazor C# file. However, you can add JavaScript to the Index. html page under the wwwroot folder in the project. That page (or any HTML page that works with Blazor), now just needs a script tag that references _framework/blazor.

Can I use JavaScript in Blazor?

A Blazor app can invoke JavaScript (JS) functions from . NET methods and . NET methods from JS functions. These scenarios are called JavaScript interoperability (JS interop).

Why is Blazor not popular?

Blazor projects are slow on the client-side because you have to download the entire dot net runtime along with the necessary DLL libraries on your browser. Additionally, Blazor apps have latency issues.

What does @inject do in Blazor?

Use the @inject directive to inject the service into components. @inject has two parameters (type and name). Type represents the service type and name represents the service instance name.


1 Answers

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>
like image 163
Flores Avatar answered Sep 29 '22 09:09

Flores