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?
