Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Cannot invoke JavaScript outside of a WebView context" error when running Javascript in Blazor Hybrid

I'm trying to use IJsruntime for importing a .js file to use in Blazor Hybrid (use in the razor component).

The service:

public class InitialDocumentHtmlService : IInitialDocumentHtmlService
{
    private readonly IJSRuntime runtime;

    public InitialDocumentHtmlService(IJSRuntime jsRuntime)
    {
        this.runtime = jsRuntime;

    }

    public async Task<string> GetColorAsync(CancellationToken token)
    {

// here u get exeption
        var helloword = await runtime.InvokeAsync<IJSObjectReference>("import", token,
            "./test.js");

        await helloword.InvokeVoidAsync("helloWorld", token);

    }
}

test.js:

export function helloWorld() {
    console.log("Hello");
    alert("hello");
}

However, it's only working in Blazor WebAssembly, while I get the following in Blazor Hybrid:

Exception:

This exception was originally thrown at this call stack:
Microsoft.AspNetCore.Components.WebView.Services.WebViewJSRuntime.BeginInvokeJS(long, string, string, Microsoft.JSInterop.JSCallResultType, long) in WebViewJSRuntime.cs
Microsoft.JSInterop.JSRuntime.InvokeAsync<TValue>(long, string, System.Threading.CancellationToken, object[])
Microsoft.JSInterop.JSRuntime.InvokeAsync<TValue>(string, System.Threading.CancellationToken, object[])
Microsoft.JSInterop.JSRuntimeExtensions.InvokeAsync<TValue>(Microsoft.JSInterop.IJSRuntime, string, System.Threading.CancellationToken, object[])
Datanex.Frontend.App.Modules.Services.InitialDocumentHtmlService.GetColorAsync(System.Threading.CancellationToken) in InitialDocumentHtmlService.cs
Datanex.Frontend.App.Modules.Services.InitialApp.InitAsync(System.Threading.CancellationToken) in InirialApp.cs
Datanex.Frontend.App.Component.Pages.Login.OnInitializedAsync() in Login.razor

Message:

Cannot invoke JavaScript outside of a WebView context.

What is causing this problem?

like image 953
madiyyarrrr Avatar asked May 01 '26 15:05

madiyyarrrr


1 Answers

Did you register IInitialDocumentHtmlService as a Singleton? I just had this issue as well and I guess in a hybrid app, the WebView isn't ready at the time your singleton service is registered yet.

In any case, I solved my issue by moving the IJSRuntime instance to the method instead of injecting it to the service:

// Change your service method:
public async Task<string> GetColorAsync(CancellationToken token, IJSRuntime js)
//...

// Then give your service this instance from the Blazor Component to ensure it's in the WebView context
@inject IJSRuntime Js; // Inject it into the Blazor component instead
// ...

GetColorAsync(ct, Js);
like image 52
Luke Vo Avatar answered May 03 '26 04:05

Luke Vo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!