5

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?

Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
Flores
  • 8,226
  • 5
  • 49
  • 81

1 Answers1

9

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>
Flores
  • 8,226
  • 5
  • 49
  • 81
  • Could you please explain how @addTagHelper is working in Blazor – Vibeeshan Mahadeva Mar 28 '18 at 05:16
  • 2
    It's because my component lives in another assembly. It's a workaround: https://github.com/aspnet/Blazor/issues/394 – Flores Mar 28 '18 at 08:32
  • Balzor.registerFunction should not be used directly in `razor` or a `component`. You will run into issue when you re-use the component. More info https://github.com/aspnet/Blazor/issues/451 – Muqeet Khan Apr 02 '18 at 17:49
  • 1
    Actually, the exposed method here should still work, as the tag is under the Router tag, it should be called once at startup. Also i imagine that we can assume that this code should be called once, we may add a static bool flagging that this component has been already initialized. – Guillaume ZAHRA Apr 03 '18 at 14:40
  • 1
    Addtionaly, on my side for my own project extension, i have created a little tool (https://github.com/Daddoon/Daddoon.Blazor/tree/master/Daddoon.JsToCsharp) that read as input args .js files, and output a BlazorComponent like .cs file. of course adapted for my project. You may use a simplistic strategy like this to maintean all your js script code outside the Blazor .cs file during development. You juste have to call the JstoCsharp tool on the PreBuild event of your package extension project. – Guillaume ZAHRA Apr 03 '18 at 14:55