skip to content

In a Blazor component, how do you call a JavaScript function through IJSRuntime, and when do you use InvokeAsync<TValue> rather than InvokeVoidAsync?

level: juniorimportance: must knowfreq 66%

answer

  1. @inject IJSRuntime JS
  2. identifier relative to window
  3. arguments and result go through JSON
  4. a returned Promise is awaited for you
  5. Interactive Server calls time out after 1 minute

basics

~10 s

Inject IJSRuntime and call InvokeAsync<TValue>("identifier", args) when you need the result, or InvokeVoidAsync when you do not. The identifier is resolved from window, arguments and results are JSON-serialized, and a returned Promise is awaited.

solid answer

~30 s

`IJSRuntime` is registered by Blazor, so a component writes `@inject IJSRuntime JS`. `InvokeAsync<TValue>(identifier, args)` calls the function found at that path from `window` (`"trailStats.compute"` means `window.trailStats.compute`), serializes the arguments with System.Text.Json using camelCase names, awaits a returned `Promise`, and deserializes the result into `TValue`. `InvokeVoidAsync` is the same call when you do not need a value. A JavaScript error comes back as a `JSException`. Overloads take a `CancellationToken` or a `TimeSpan`; on Interactive Server every call otherwise times out after `CircuitOptions.JSInteropDefaultCallTimeout`, one minute, while WebAssembly applies no default timeout. ASP.NET Core 10 adds `InvokeConstructorAsync`, `GetValueAsync` and `SetValueAsync` for constructors and properties.

code

razor · 20 lines
razor
@inject IJSRuntime JS

<button @onclick="ShareAsync">Copy link</button>
<button @onclick="DeleteAsync">Delete trail</button>

@code {
    [Parameter] public Trail Trail { get; set; } = default!;

    private async Task ShareAsync() =>
        await JS.InvokeVoidAsync("navigator.clipboard.writeText", Trail.ShareUrl);

    private async Task DeleteAsync()
    {
        var confirmed = await JS.InvokeAsync<bool>("confirm", $"Delete {Trail.Name}?");
        if (confirmed)
        {
            await TrailService.DeleteAsync(Trail.Id);
        }
    }
}

go deeper

for a junior

Recall @inject IJSRuntime, InvokeAsync<T> for a result and InvokeVoidAsync without one, and that the identifier is a path from window.

for a middle

Explain JSON serialization, promise unwrapping, JSException, the 1-minute server timeout and the CancellationToken and TimeSpan overloads.

for a senior

Keep interop chatty-free on Interactive Server, prefer modules over globals, and handle timeouts and disconnects deliberately.

for a principal

Set a team boundary for JavaScript: which features stay in .NET, which move to modules, and how interop cost is budgeted per render mode.

## The service and its two everyday calls Blazor registers **`IJSRuntime`** in every hosting model, so a component asks for it with `@inject IJSRuntime JS` (or a class takes it through its constructor). Two calls cover most work: | Call | Returns | Use when | |---|---|---| | `InvokeAsync<TValue>(identifier, params object?[] args)` | `ValueTask<TValue>` | The JavaScript function returns something you need | | `InvokeVoidAsync(identifier, params object?[] args)` | `ValueTask` | You only need the call to finish | `InvokeVoidAsync` is an extension method that performs the same invocation and discards the result. Both are asynchronous in every hosting model because on Interactive Server the call crosses a SignalR connection to the browser. ## How the identifier and the data travel 1. **Identifier.** A dotted path resolved from the global scope (`window`): `"confirm"` is `window.confirm`, `"navigator.clipboard.writeText"` walks the properties. Nothing has to be registered first, which is also why global functions are fragile in a large app; JavaScript modules (see `IJSObjectReference`) avoid the global namespace. 2. **Arguments.** Serialized to JSON with System.Text.Json, camelCase property names and a maximum depth of 32. An `ElementReference` arrives as the DOM element, a `DotNetObjectReference` as a callable proxy. 3. **Result.** If the function returns a `Promise`, Blazor awaits it, then deserializes the settled value into `TValue` (case-insensitively). Ask for `IJSObjectReference` as `TValue` to keep a handle on a JavaScript object instead of copying it. 4. **Errors.** An exception thrown in JavaScript, or a rejected promise, surfaces in .NET as `Microsoft.JSInterop.JSException` with the JavaScript message. ## Timeouts and cancellation - On **Interactive Server**, `RemoteJSRuntime` applies `CircuitOptions.JSInteropDefaultCallTimeout`, which defaults to **1 minute**; a call still pending then is cancelled and the awaiting code sees a `TaskCanceledException`. - On **WebAssembly** no default timeout applies. - Every call has overloads taking a `CancellationToken` or a `TimeSpan` timeout, so one long operation can get its own limit without changing the circuit-wide default. - In WebAssembly, `IJSRuntime` can be cast to **`IJSInProcessRuntime`** for synchronous `Invoke<TValue>` and `InvokeVoid`; that is not possible on the server, where every call is a network round trip. ## New in ASP.NET Core 10 ASP.NET Core 10 adds three members to `IJSRuntime` and `IJSObjectReference`: - `InvokeConstructorAsync(identifier, args)` runs a JavaScript constructor with `new` and returns an `IJSObjectReference` to the instance. - `GetValueAsync<TValue>(identifier)` reads a JavaScript property. - `SetValueAsync<TValue>(identifier, value)` writes one, creating it if it does not exist. Before 10 each of these needed a small wrapper function written in JavaScript. ## What a call costs in each hosting model The same line of C# has very different costs depending on where the component runs: - **Interactive Server:** each call is a SignalR message to the browser and a reply back, so it costs a network round trip. Ten calls in a loop are ten round trips; send one array to a function that loops in JavaScript instead. - **Interactive WebAssembly:** the call stays in the browser tab, but arguments still go through JSON serialization, which matters for large payloads or thousands of calls. - **Static SSR and prerendering:** there is no browser connection at all, so any call throws an `InvalidOperationException`. - **Large data:** for big byte arrays or files, the interop layer has stream types (`DotNetStreamReference`, `IJSStreamReference`) rather than one huge JSON argument. Keeping interop coarse-grained is the main design rule: one call that does a meaningful unit of work beats many small calls that each wait for the browser. ## Practical rules - Prefer a function that returns a small, serializable result. Returning a large DOM structure or a cyclic object fails serialization or wastes bandwidth on Interactive Server. - Use `InvokeVoidAsync` for fire-and-confirm calls such as focusing or copying; asking for `InvokeAsync<object>` just to ignore the result adds deserialization work. - Call JavaScript only once the component has rendered interactively; during prerendering or static rendering there is no browser to call (`OnAfterRenderAsync` with `firstRender` is the usual place). - Wrap calls that may hit a lost circuit, especially in disposal, and expect `JSDisconnectedException` there.

  • A call to a slow JavaScript export routine fails after exactly one minute on Interactive Server but works in WebAssembly; why?
    Interactive Server applies `CircuitOptions.JSInteropDefaultCallTimeout`, one minute by default, to every call without its own token; the pending call is cancelled and surfaces as a `TaskCanceledException`. WebAssembly sets no default timeout. Pass a `TimeSpan` or `CancellationToken` overload for that call, or raise the option in `AddInteractiveServerComponents(o => ...)`.
  • A JavaScript function returns { trailName: 'Ridge Loop' } and the C# record has a TrailName property; does it bind?
    Yes. JS interop serializes with System.Text.Json using camelCase names and reads results case-insensitively, so `trailName` fills `TrailName`. The same options send C# properties to JavaScript in camelCase, which is what most JavaScript code expects.

  • Functions must be registered with Blazor before IJSRuntime can call them.
  • InvokeVoidAsync fires the call and does not wait for a returned promise.
  • JS interop calls have no timeout unless you pass a CancellationToken.
  • IJSRuntime calls can be made synchronously in an Interactive Server component.
  • A JavaScript exception is swallowed and the call returns default(TValue).

Assumes ASP.NET Core 10; InvokeConstructorAsync, GetValueAsync and SetValueAsync are new in 10, and the 1-minute default timeout is CircuitOptions.JSInteropDefaultCallTimeout on Interactive Server.