Blazor Javascript Interop
In components, inject the IJSRuntime (no need to register it).
@inject IJSRuntime JsRuntime
Calling into javascript is always async (wrapped in a js promise)
_currentLanguage = await JsRuntime.InvokeAsync<string>("localStorage.getItem", "currentLanguage");
await JsRuntime.InvokeVoidAsync("localStorage.setItem", "currentLanguage", "fr-Fr");
await JsRuntime.InvokeVoidAsync("localStorage.setItem", "currentLanguage", "fr-Fr");
Capture ElementReference with @ref and use the OnAfterRenderAsync event, not OnInitialized
<div @ref="_myElement"></div>
@code {
//capture the @ref element reference
private ElementReference _myElement;
//use OnAfterRenderAsync for js using an ElementReference- as it must have been rendered
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await JsRuntime.InvokeVoidAsync("myFunction", _myElement);
}
}
@code {
//capture the @ref element reference
private ElementReference _myElement;
//use OnAfterRenderAsync for js using an ElementReference- as it must have been rendered
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await JsRuntime.InvokeVoidAsync("myFunction", _myElement);
}
}