Advertisement
Intermediate .NET, Blazor (Server & WebAssembly)

How do you call JavaScript from C# code in Blazor (JS interop), and when is it necessary?

Short answer

IJSRuntime.InvokeAsync ("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)…

Save .NET mock interview
Advertisement
AModel answer
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.
Likely follow-ups
  • How does JS interop performance differ between Blazor Server (network round-trip) and WebAssembly (in-process)?
  • How do you call C# methods FROM JavaScript (the reverse direction)?
Related topics