Automatically use javascript in blazor application

I am developing a Blazor extension library.

One thing in this library will be reusing the javascript alert () method. I know how to do this, this is due to adding this to the .cshtml page:

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

and this is in my code:

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

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

Any ideas on this?

+2
source share
1 answer

I ended up creating my own blazor component containing my javascript, for example:

 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 as follows:

 @addTagHelper *, BlazorExtensions <Router AppAssembly=typeof(Program).Assembly /> <BlazorExtensionScripts></BlazorExtensionScripts> 
+4
source

Source: https://habr.com/ru/post/1276054/


All Articles