javascriptdependency-injectionblazorwebassembly

Blazor - Call JavaScript from C# class


Here is what I want to achieve:

I have a (normal) class in a Blazor WASM project. I want to invoke a JavaScript function from my class. If I want to do this from a Razor component it is working fine, I inject IJSruntime and invokevoidasync to my JavaScript.

But it goes wrong when I try to do it from a class. First I tried to inject it like this:

[Inject]
IJSRuntime JSRuntime { get; set; }

But ended up with error message: Value cannot be null. (Parameter 'jsRuntime') I learned from this post that I have to "Inject it in the traditonal way", so I did this:

public class InvokeJavaScript
{
    private readonly IJSRuntime jSRuntime;

    public InvokeJavaScript(IJSRuntime jSRuntime)
    {
        this.jSRuntime = jSRuntime;
    }

    public async void InvokeMyJs()
    {
        await jSRuntime.InvokeVoidAsync("giveMeAMessage");
    }
}

But from there on I am stuck, I know that this must be some key .NET knowledge but I am missing a piece here.. I want to call the "InvokeMyJs" methode like:

InvokeJavaScript ij = new InvokeJavaScript();
ij.InvokeMyJs();

But know I am facing an error: There is no argument given that corresponds to the required formal parameter 'jSRuntime' of 'InvokeJavaScript.InvokeJavaScript(IJSRuntime)'

That I get the error makes sense to me but I dont know how to fix it, what parameter must I send to InvokeJavaScript(IJSRuntime jSRuntime) and how do I do it correctly? Can anyone give an example?


Solution

  • Initialize the class from the .razor page in @code {}

    @inject IJSRuntime JsRuntime
      @code {
       protected override void OnInitialized()
       {
           InvokeJavaScript = new(JsRuntime);
       }}