How does Blazor communicate with JavaScript, and what is the difference between InvokeAsync and InvokeVoidAsync?
Last updated
Blazor talks to JavaScript through the IJSRuntime abstraction (JS interop): InvokeAsync<T> calls a JS function and returns its result, while InvokeVoidAsync calls one when you don't need a return value.
The interop channel:
Inject
IJSRuntime; arguments and results are JSON-serialized, so pass serializable data.In Blazor Server the calls cross the SignalR circuit (network latency), so interop is always async.
InvokeAsync<T>: Use when JS returns a value;Tis the deserialized return type (e.g.InvokeAsync<string>).InvokeVoidAsync: Use for fire-and-forget-style calls with no result (e.g.localStorage.setItem, focusing an element); it's just the void-returning convenience overload.Timing caveat: Interop needs a rendered DOM, so avoid it in
OnInitialized; do it inOnAfterRenderAsync.
[lang:csharp]
// Returns a value
var text = await JS.InvokeAsync<string>("localStorage.getItem", "token");
// No return value
await JS.InvokeVoidAsync("localStorage.setItem", "token", token);
- https://learn.microsoft.com/en-us/aspnet/core/blazor/javascript-interoperability/call-javascript-from-dotnet?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/blazor/javascript-interoperability/?view=aspnetcore-10.0
- https://blazor-university.com/javascript-interop/calling-javascript-from-dotnet/
- https://oneuptime.com/blog/post/2026-01-30-custom-jsinterop-blazor/view