
While Blazor WASM runs C# in the browser, you sometimes need to call JavaScript — for browser APIs, third-party JS libraries, or DOM manipulation Blazor cannot do natively.
@inject IJSRuntime JS
// Void call:
await JS.InvokeVoidAsync("console.log", "Hello from C#!");
// Call that returns a value:
string result = await JS.InvokeAsync<string>("getLocalStorageItem", "token");// wwwroot/app.js
window.showAlert = (message) => alert(message);
window.scrollToTop = () => window.scrollTo(0, 0);// C# — mark method as invokable:
[JSInvokable]
public static string GetGreeting() => "Hello from .NET!";
// JS:
const result = await DotNet.invokeMethodAsync('MyApp', 'GetGreeting');Use IJSRuntime.InvokeAsync<IJSObjectReference> to import a JS module and avoid polluting the global window scope.
Reference:
TaskLoco™ — The Sticky Note GOAT