I am trying to call a JavaScript function in a .razor component:
This is what it's been declared like in index.html:
window.getIsBrowserChromium = function () {
return !!navigator.userAgentData &&
navigator.userAgentData.brands.some(data => data.brand == 'Chromium');
}
This is how it is being called:
public async Task<bool> GetIsChromium() =>
await JSRuntime.InvokeAsync<bool>("window.getIsBrowserChromium");
And this is how it's being used in the MainLayout:
protected async override Task OnInitializedAsync()
var isChromiumBrowser = await BrowserService.GetIsChromium();
if (!isChromiumBrowser)
{
ShowBrowserWarning();
}
}
I tried using OnAfterRenderAsync() instead but same results.
The error says it can't find
window.getIsBrowserChromium
, so you can't have it registered properly.I've moved your JS code into wwwroot/site.js, and then added the reference to _hosts.cshtml.
To demo the check. I've added the JSInterop call to
OnAfterRenderAsync
. As this mutates the state of the component you need to callStateHasChanged
to reflect that change in the UI.Run in Edge : True Firefox: False