JavaScript Isolation in Blazor WebAssembly

From the .NET 5 (RC 1) version, we are able to isolate our JavaScript code as a standard JavaScript module.

This is beneficial because

  • We no longer have to add our JS functions to the global window namespace
  • We don’t have to manually import JavaScript files in the index.html file

myscript.js

export function doSomething() {
    document.getElementById('txtField').value = "";
    document.getElementById('txtField').focus();
}

Razor Page

[Inject]
public IJSRuntime jsRuntime { get; set; }
private IJSObjectReference jsModule;

protected override async Task OnInitializedAsync()
{
     jsModule = await jsRuntime.InvokeAsync<IJSObjectReference>("import", "./js/myscript.js");
}

public async Task SomethingOnChange(ChangeEventArgs args)
{
	await jsModule.InvokeAsync<object>("doSomething");
}

Sources:

Last modified: June 13, 2021

Author

Comments

Write a Reply or Comment