Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 41 ยท JS Interop and Auth

JavaScript Interop Basics

Call JavaScript from Blazor with IJSRuntime, pass and return values, handle errors and prerendering, and know when interop is worth it. Includes a runnable C# stand-in.

Blazor lets you build interfaces without writing JavaScript, but the browser is full of features only JavaScript can reach: localStorage, the clipboard, geolocation, focus management, canvas drawing, third-party widgets such as maps and charts. JavaScript interop (JS interop) is the bridge. Your C# code asks the browser to run a JavaScript function and gets the result back, and JavaScript can call into your C# in return.

This lesson covers the first direction, C# to JavaScript, with IJSRuntime. You will learn the call shapes, how values are serialized, why interop is asynchronous (and what that means on the server), when it is safe to call, and how to handle errors. The framework calls are read-only snippets; the runnable stand-in is a fake JS runtime in C# that follows the same rules, so you can see what travels across the bridge.

Why interop is always asynchronous

In Blazor WebAssembly, C# and JavaScript share a thread in the browser, so a call could be synchronous. In Blazor Server, C# runs on a server and the browser is across the network: the call becomes a message over SignalR and the result is a reply message. To make code portable between modes, the standard API is async: InvokeAsync and InvokeVoidAsync, both returning ValueTask. Always await them.

Your first call

Write a plain script in wwwroot (or in the host page) that attaches functions to window:

HTML
<script>
  window.demo = {
    greet: (name) => `Hello, ${name}!`,
    focusElement: (element) => element.focus(),
    copy: (text) => navigator.clipboard.writeText(text),
  };
</script>

Then call it from a component through the injected IJSRuntime:

RAZOR
@inject IJSRuntime JS

<input @ref="box" />
<button @onclick="Greet">Greet</button>
<p>@message</p>

@code {
    private ElementReference box;
    private string message = "";

    private async Task Greet()
    {
        message = await JS.InvokeAsync<string>("demo.greet", "Maria");
        await JS.InvokeVoidAsync("demo.focusElement", box);
    }
}
  • InvokeAsync<T>(identifier, args) calls the function at that path from window (dots navigate objects) and deserializes the return value to T.
  • InvokeVoidAsync is for functions with no useful result.
  • ElementReference (from @ref) is passed as a DOM element, which lets scripts act on a specific element without searching by id.

Serialization

Everything crossing the bridge is serialized as JSON. Arguments become JSON on the way out; the result is JSON on the way back. Consequences:

  • Primitives, strings, arrays, lists, dictionaries and plain objects (DTOs) work.
  • Functions, DOM nodes (except ElementReference), circular structures and C# types with no JSON form do not.
  • Property names follow System.Text.Json web defaults: C# FirstName becomes firstName.
  • Large payloads are slow on Blazor Server: every byte goes over the wire. A 5 MB array is a very bad idea. For binary data use IJSStreamReference / DotNetStreamReference, which stream chunks.
  • Blazor Server has a message-size limit for SignalR (32 KB by default for one incoming message); bigger values need streaming or chunking.

The stand-in below plays the role of the browser. It stores "JavaScript functions" as lambdas that receive JSON arguments, so you can watch the serialization and the failure cases.

C# Stand-in IJSRuntime

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Notice the three behaviors that matter in real apps: names are looked up on window, failures surface as a JSException in C#, and during static rendering there is no browser to call.

When is it safe to call JavaScript?

On the server, a component is first rendered to HTML (prerendering) before any browser is connected. If you call JS.InvokeAsync in OnInitializedAsync during that phase you get an InvalidOperationException. The rules:

  • Call JS from OnAfterRenderAsync, typically guarded by firstRender. The DOM exists and interactivity has started.
  • Or call it from event handlers, which only run when interactive.
  • Wrap uncertain calls in try/catch (JSDisconnectedException) on Blazor Server: the user may have closed the tab, so the circuit is gone and the call fails. Ignoring this exception during disposal is the normal practice.
RAZOR
@inject IJSRuntime JS

@code {
    private string theme = "light";

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            theme = await JS.InvokeAsync<string>("localStorage.getItem", "theme") ?? "light";
            StateHasChanged();     // re-render with the loaded value
        }
    }
}

Timeouts and cancellation

Server calls can hang if the browser is slow or the connection stalls. Pass a CancellationToken or TimeSpan as the first argument to set a limit:

C#
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
var location = await JS.InvokeAsync<GeoPoint>("geo.current", cts.Token);

Without it, the default timeout is one minute on Blazor Server.

Using JS interop wisely

Ask first: can C# do this? Prefer Blazor features (@bind, @onclick, NavigationManager, ElementReference.FocusAsync()) over interop. Where interop is the right answer:

  • Browser APIs without a Blazor wrapper (clipboard, geolocation, matchMedia, notifications).
  • Existing JavaScript libraries (maps, charts, rich-text editors).
  • DOM measurements (element size, scroll position).

Wrap each use in a C# service that hides the strings:

C#
public class ClipboardService(IJSRuntime js)
{
    public ValueTask CopyAsync(string text) => js.InvokeVoidAsync("navigator.clipboard.writeText", text);
}

Components depend on ClipboardService, never on "navigator.clipboard.writeText" literals scattered across files. You can replace the service with a fake in tests, exactly like the stand-in above. The next lesson shows how to load scripts as isolated modules and call C# from JavaScript: JS Modules and Calling .NET from JavaScript.

A wrapper service on top of the stand-in

C# Interop behind a service

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Never pass untrusted strings to eval or build JavaScript source from user input. Call named functions with arguments; the interop layer escapes them as JSON.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why are Blazor JS interop calls asynchronous?

    On the server, a JS call is a message to the browser and a reply back, so it must be awaited; the same API is used for all hosting models.
  2. 2. Where should you call JavaScript to read localStorage when the component first appears?

    During prerendering no browser exists; after the first render the DOM and the connection are ready.
  3. 3. How are arguments and return values transferred?

    Values are serialized to JSON in both directions, so functions and circular objects cannot cross.
  4. 4. What exception reports an error thrown by the JavaScript function?

    JavaScript errors surface in C# as JSException with the JavaScript message.

Summary

  • IJSRuntime.InvokeAsync<T> and InvokeVoidAsync call functions on window; always await them.
  • Data crosses as JSON; use streams for large or binary data.
  • Call JS from OnAfterRenderAsync or event handlers, never during prerendering; catch JSDisconnectedException on the server.
  • Wrap interop in C# services so components stay clean and testable.
  • Prefer built-in Blazor features, and never evaluate user-supplied script.

Next: JS Modules and Calling .NET from JavaScript