.NET › Blazor (Server & WebAssembly)
How do you call JavaScript from C# code in Blazor (JS interop), and when is it necessary?
IntermediateAnswer
IJSRuntime.InvokeAsync<T>("functionName", args) calls a JavaScript function from C# and awaits its result, necessary for accessing browser APIs Blazor doesn't wrap natively (like localStorage, certain DOM APIs, or existing third-party JS libraries like chart rendering libraries) that don't have a direct Blazor equivalent.
@inject IJSRuntime JS
<button @onclick="ShowAlert">Alert</button>
@code {
private async Task ShowAlert() {
await JS.InvokeVoidAsync("alert", "Hello from Blazor!");
}
}Real-world example A Blazor dashboard integrates an existing JavaScript charting library (like Chart.js) via JS interop, since no mature native Blazor charting component existed that matched the team's exact visualization requirements.