0

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?

4
  • 1
    You need to provide your class InvokeJavaScript for injection. Something like services.AddScoped<InvokeJavaScript>().... Commented Aug 5, 2021 at 9:48
  • Ok, I added that to my startup class, but how to go from there? Commented Aug 5, 2021 at 9:56
  • 1
    This class is then injectable. You can then inject it into any component you want. Commented Aug 5, 2021 at 10:05
  • 1
    Also, be very carful with async void. Better make it async Task and await it unless you are very very sure you need fire&forget mode. Commented Aug 5, 2021 at 10:13

1 Answer 1

2

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

@inject IJSRuntime JsRuntime
  @code {
   protected override void OnInitialized()
   {
       InvokeJavaScript = new(JsRuntime);
   }}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.