In the SharpRune app for iPhone and iPad, tap Run in Preview: the app compiles the Razor components on the device and runs the project on .NET 9. On a computer, download the project and run it with the .NET 9 SDK. The separate C# companion practice below runs in this browser.
Two worlds joined by a bridge
IJSRuntime in the Interop pagefirst calls go in OnAfterRenderAsync when firstRender is true["jsbridge-note","Buy milk"] crosses as JSON; objects cross as handle idsjsLab and ./js/scroll.jsinvokeMethodAsync('OnScroll', y) calls the [JSInvokable] methodlocalStorage, scroll eventsC# reaches them only through this bridgeEvery call is an async message, and handles keep objects alive on the other side. DisposeAsync stops the watcher, releases the module, then disposes the DotNetObjectReference last.
What crosses the bridge
In Blazor WebAssembly, the .NET runtime runs inside the browser next to JavaScript, but the two worlds keep separate objects. A call through IJSRuntime is a message. Blazor serializes the arguments to JSON with System.Text.Json and camelCase names, finds the JavaScript function by its identifier, calls it, waits if it returns a promise, serializes the result and deserializes it into your T. The companion prints that JSON: the arguments of localStorage.setItem become a JSON array, and a C# record becomes an object with camelCase keys.
Some things cannot travel as JSON, such as a DOM element, a function, or an object with its own behavior. For those, Blazor passes handles. An IJSObjectReference stands for a JavaScript object that stays on the JavaScript side; Blazor keeps it in a table and sends only an id. A DotNetObjectReference does the same in the other direction for a .NET object. An ElementReference, which you get with @ref, lets JavaScript receive an element that Blazor rendered.
Every call in the IJSRuntime API is asynchronous and returns a ValueTask, so the same code works in every hosting model. WebAssembly also offers IJSInProcessRuntime for synchronous calls, but the async API is the one to learn first.
Global functions and modules
An identifier such as jsLab.browserInfo is a path from window. Blazor walks the path, finds the function, and calls it with the object before the last dot as this. That is why browser methods such as localStorage.getItem work without any JavaScript of your own. Global functions are quick to write in a script tag in index.html, as the project does for jsLab. Their cost is that every name shares one global namespace, and the script must load before Blazor calls it.
A JavaScript module keeps its names private and loads only when needed. The special identifier import makes Blazor run a dynamic import, and the result is an IJSObjectReference for the module. You call its exported functions with module.InvokeAsync and module.InvokeVoidAsync. The path ./js/scroll.js is resolved against the <base href>, so it points at wwwroot/js/scroll.js. The browser loads a module only once per URL, even if several components import it.
A JavaScript function may also return an object, and Blazor can hand it to .NET as an IJSObjectReference instead of JSON. watchScroll in the project does that: it returns an object with a stop method, and the component keeps it as watcher.
Why the first calls wait for OnAfterRenderAsync
Before the first render finishes, the component's elements are not in the document. Any JavaScript that reads or changes them must wait. In apps that prerender on a server, JavaScript is not available at all during prerendering, and calls made in OnInitialized throw. OnAfterRenderAsync with firstRender set to true avoids both problems, so the habit is to start interop there.
OnAfterRenderAsync does not cause another render when it completes. If you change fields there, as the Interop page does with info and stored, call StateHasChanged yourself. Guard that call with the firstRender check. Calling StateHasChanged on every after-render pass starts a new render, which runs OnAfterRenderAsync again, and the loop never ends.
JavaScript calling .NET
DotNetObjectReference.Create(this) wraps the component. When you pass it as an argument, JavaScript receives an object with invokeMethodAsync. Calling invokeMethodAsync('OnScroll', y) finds the public method marked [JSInvokable] with that name, deserializes y into an int and runs it. The method may return a value, which comes back to JavaScript as the result of the promise.
Blazor does not know that a JavaScript call changed your fields, so OnScroll calls StateHasChanged. Browser events such as scroll can fire many times per second. The module therefore sends at most one call per animation frame with requestAnimationFrame. Without that, the page would make hundreds of interop calls and render for each one.
The wrapper keeps the component reachable from JavaScript. While it exists, the component cannot be garbage collected, and JavaScript can still call it. That is why the reference must be disposed.
Disposal, in the right order
The Interop page implements IAsyncDisposable. When you navigate away, the Router removes the page and Blazor calls DisposeAsync. The method first calls stop on the watcher, so JavaScript removes its scroll listener and no new calls start. Then it disposes the watcher and the module references, which lets the JavaScript side forget those objects. Last, it disposes the DotNetObjectReference. If the order were reversed, a scroll event could arrive after the .NET reference was released, and JavaScript would get an error about an object that is no longer tracked.
The After dispose page proves the cleanup. It calls the global function jsLab.listenerCount, which reads a counter that watchScroll increases and stop decreases. After every visit to Interop it shows 0. In Blazor Server, JavaScript calls in DisposeAsync can throw JSDisconnectedException when the connection is already gone, so server code catches it there. WebAssembly has no such connection.
Trace the JS Bridge project
The first render shows 'Waiting for the first render…'. Then OnAfterRenderAsync runs with firstRender true. jsLab.browserInfo returns an object, which is read into the BrowserInfo record. localStorage.getItem returns null, so the page shows 'nothing yet'. The module is imported, the component is wrapped, and watchScroll receives the wrapper and returns the watcher. StateHasChanged renders the real values.
Save calls localStorage.setItem with InvokeVoidAsync and reads the value back with InvokeAsync. Scrolling calls OnScroll at most once per frame, and the bar shows the position and the count. Top calls the module's scrollToTop, and the scroll events that follow bring the value back to 0. Navigating to After dispose runs DisposeAsync and then the listener count.
Common mistakes, practice and review
Common mistakes: calling JavaScript in OnInitialized when the app prerenders; forgetting StateHasChanged after a JavaScript callback; never disposing references, so listeners pile up and old components keep receiving calls; letting JavaScript change elements whose content Blazor renders, which leaves Blazor's picture of the page out of date; returning a DOM node or an object with cycles as if it were JSON. In SharpRune's Preview, avoid alert and prompt, which block the page, and do not rely on localStorage between runs.
Practice: comment out the stop call in DisposeAsync, visit Interop three times, and predict the count on the After page before you look. Add a parameter to watchScroll that sets a minimum distance in pixels, and call .NET only when the position changed by that much. Add a second [JSInvokable] method that JavaScript calls on the visibilitychange event, and show whether the page is visible.
InvokeAsync<T>andInvokeVoidAsynccall JavaScript by a path from window; arguments and results travel as JSON.- import returns an IJSObjectReference for a module; dispose it when the component goes away.
- Start interop in
OnAfterRenderAsyncwhenfirstRenderis true, and callStateHasChangedif you changed state. DotNetObjectReferenceand[JSInvokable]let JavaScript call a component; dispose the reference last.
Calling JavaScript — Blazor WebAssembly project
Run the project
- Tap Run in Preview. SharpRune copies these files into a new project, compiles the Razor components on this device and opens the app in Preview.
- Type a note and tap Save. Then scroll down and watch the dark bar count calls from JavaScript, and tap Top to scroll back through a module function.
- Open After dispose in the header and read the listener count. Go back to Interop, then open After dispose again.
- Change a .razor file and tap Run again to rebuild.
- On a computer: install the .NET 9 SDK, save the files with their folders, and run dotnet run in that folder.
Project files
JsBridge.csproj
Download file ↗<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<AssemblyName>JsBridge</AssemblyName>
<RootNamespace>JsBridge</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="9.0.4" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="9.0.4" PrivateAssets="all" />
</ItemGroup>
</Project>
Program.cs
Download file ↗using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using JsBridge;
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");
// IJSRuntime is registered by default. Components receive it with @inject.
await builder.Build().RunAsync();
App.razor
Download file ↗@* The root component. This small app has no layout file,
so the shared header sits here, around the Router. *@
<header class="bar">
<span class="brand">JS Bridge</span>
<nav>
<NavLink href="" Match="NavLinkMatch.All">Interop</NavLink>
<NavLink href="after">After dispose</NavLink>
</nav>
</header>
<main>
<Router AppAssembly="@typeof(App).Assembly">
<Found Context="routeData">
<RouteView RouteData="@routeData" />
<FocusOnNavigate RouteData="@routeData" Selector="h1" />
</Found>
<NotFound>
<PageTitle>Not found</PageTitle>
<h1>Not found</h1>
<p>There is no page at this address.</p>
</NotFound>
</Router>
</main>
_Imports.razor
Download file ↗@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using Microsoft.JSInterop
@using JsBridge
Pages/After.razor
Download file ↗@page "/after"
@inject IJSRuntime JS
<PageTitle>After dispose</PageTitle>
<h1>After dispose</h1>
<p>When you left the interop page, Blazor called its <code>DisposeAsync</code>. It stopped the scroll listener and released the module, the watcher and the DotNetObjectReference.</p>
<p class="value" role="status">Scroll listeners attached right now: @(count?.ToString() ?? "checking…")</p>
<button @onclick="CheckAsync">Check again</button>
<p class="muted">Go back to Interop and the count is 1 while that page is open. Without DisposeAsync, every visit would leave one more listener behind.</p>
@code {
private int? count;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await CheckAsync();
StateHasChanged();
}
}
private async Task CheckAsync() =>
count = await JS.InvokeAsync<int>("jsLab.listenerCount");
}
Pages/Interop.razor
Download file ↗@page "/"
@implements IAsyncDisposable
@inject IJSRuntime JS
<PageTitle>JS interop</PageTitle>
<h1>Calling JavaScript</h1>
<section class="card">
<h2>1. A global function</h2>
<p>Read after the first render with <code>InvokeAsync<BrowserInfo>("jsLab.browserInfo")</code>.</p>
@if (info is null)
{
<p class="value">Waiting for the first render…</p>
}
else
{
<p class="value">@info.Language · @info.Width × @info.Height px · touch: @(info.Touch ? "yes" : "no")</p>
}
<button @onclick="ReadInfoAsync">Read again</button>
</section>
<section class="card">
<h2>2. A browser built-in</h2>
<p><code>InvokeVoidAsync("localStorage.setItem", …)</code> writes, <code>InvokeAsync<string?>("localStorage.getItem", …)</code> reads.</p>
<div class="row">
<input @bind="note" placeholder="A note to keep" aria-label="Note" />
<button class="primary" @onclick="SaveNoteAsync">Save</button>
</div>
<p class="value">localStorage has: @(stored ?? "nothing yet")</p>
</section>
<section class="card">
<h2>3. A module that calls .NET</h2>
<p>The module <code>js/scroll.js</code> listens to window scrolling and calls the <code>[JSInvokable]</code> method <code>OnScroll</code>. Scroll down.</p>
<div class="sticky" role="status">
<span>Scrolled @scrollY px · calls from JS: @callbacks</span>
<button class="primary" @onclick="ScrollToTopAsync">Top</button>
</div>
<ol class="filler">
@for (var i = 1; i <= 30; i++)
{
<li>Row @i</li>
}
</ol>
</section>
@code {
private const string NoteKey = "jsbridge-note";
private BrowserInfo? info;
private string note = "";
private string? stored;
private int scrollY;
private int callbacks;
private IJSObjectReference? module;
private IJSObjectReference? watcher;
private DotNetObjectReference<Interop>? selfRef;
// JavaScript can only reach the page after it is in the browser,
// so the first calls happen here and not in OnInitialized.
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (!firstRender) return;
info = await JS.InvokeAsync<BrowserInfo>("jsLab.browserInfo");
stored = await JS.InvokeAsync<string?>("localStorage.getItem", NoteKey);
// import() returns the module; IJSObjectReference keeps a handle to it.
module = await JS.InvokeAsync<IJSObjectReference>("import", "./js/scroll.js");
// A handle JavaScript can use to call [JSInvokable] methods on this component.
selfRef = DotNetObjectReference.Create(this);
watcher = await module.InvokeAsync<IJSObjectReference>("watchScroll", selfRef);
// Changes made in OnAfterRenderAsync need an explicit render.
StateHasChanged();
}
private async Task ReadInfoAsync() =>
info = await JS.InvokeAsync<BrowserInfo>("jsLab.browserInfo");
private async Task SaveNoteAsync()
{
await JS.InvokeVoidAsync("localStorage.setItem", NoteKey, note);
stored = await JS.InvokeAsync<string?>("localStorage.getItem", NoteKey);
}
private async Task ScrollToTopAsync()
{
if (module is not null)
{
await module.InvokeVoidAsync("scrollToTop");
}
}
// JavaScript calls this with dotNetRef.invokeMethodAsync("OnScroll", y).
[JSInvokable]
public void OnScroll(int y)
{
scrollY = y;
callbacks++;
// The call came from JavaScript, not from a Blazor event handler, so ask for a render.
StateHasChanged();
}
// Runs when you leave the page. Stop the listener, then release every handle.
public async ValueTask DisposeAsync()
{
if (watcher is not null)
{
await watcher.InvokeVoidAsync("stop");
await watcher.DisposeAsync();
}
if (module is not null)
{
await module.DisposeAsync();
}
selfRef?.Dispose();
}
// The JSON object from jsLab.browserInfo() fills this record: "language" goes to Language, and so on.
public sealed record BrowserInfo(string Language, int Width, int Height, bool Touch);
}
wwwroot/index.html
Download file ↗<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>JS Bridge</title>
<base href="/" />
<link rel="stylesheet" href="css/app.css" />
<link rel="stylesheet" href="JsBridge.styles.css" />
</head>
<body>
<div id="app">
<p class="loading">Starting .NET…</p>
</div>
<div id="blazor-error-ui">
An unhandled error has occurred.
<a href="." class="reload">Reload</a>
<span class="dismiss">✕</span>
</div>
<script>
// Global functions. .NET calls them by their path from window, for example "jsLab.browserInfo".
window.jsLab = {
listeners: 0,
browserInfo: function () {
return {
language: navigator.language,
width: window.innerWidth,
height: window.innerHeight,
touch: navigator.maxTouchPoints > 0
};
},
listenerCount: function () {
return window.jsLab.listeners;
}
};
</script>
<script src="_framework/blazor.webassembly.js"></script>
</body>
</html>
wwwroot/css/app.css
Download file ↗:root {
color-scheme: light dark;
--accent: #6b4eff;
--line: #d8d6e4;
--danger: #d32f2f;
--ok: #2e7d32;
}
body {
margin: 0;
font-family: -apple-system, system-ui, sans-serif;
line-height: 1.5;
}
a, button, input, label { touch-action: manipulation; }
select { touch-action: manipulation; }
.bar {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px 16px;
padding: 12px 16px;
background: #1f1b3a;
color: #fff;
}
.brand {
font-weight: 700;
margin-right: auto;
}
.bar nav {
display: flex;
gap: 4px;
}
.bar nav a {
color: #d9d4ff;
text-decoration: none;
padding: 6px 10px;
border-radius: 8px;
}
.bar nav a.active {
background: var(--accent);
color: #fff;
}
main {
padding: 20px 16px 40px;
max-width: 720px;
margin: 0 auto;
box-sizing: border-box;
}
h1 {
font-size: 1.8rem;
margin: 0 0 12px;
}
h1:focus {
outline: none;
}
h2 {
font-size: 1.15rem;
margin: 24px 0 8px;
}
.loading {
padding: 32px 16px;
color: #777;
}
.muted {
color: #777;
}
.row {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin: 12px 0;
}
input:not([type=checkbox]), select, textarea {
font: inherit;
color: inherit;
background: transparent;
padding: 8px 10px;
border: 1px solid var(--line);
border-radius: 8px;
min-width: 0;
box-sizing: border-box;
}
button {
font: inherit;
padding: 8px 14px;
border-radius: 8px;
border: 1px solid var(--line);
background: transparent;
color: inherit;
}
button.primary {
background: var(--accent);
border-color: var(--accent);
color: #fff;
}
button:disabled {
opacity: 0.45;
}
button.link {
border: none;
color: var(--accent);
padding: 4px 6px;
}
code {
font-size: 0.9em;
overflow-wrap: anywhere;
}
#blazor-error-ui {
display: none;
position: fixed;
bottom: 0;
left: 0;
right: 0;
padding: 12px 16px;
background: #ffe8a3;
color: #222;
}
.card {
margin: 0 0 16px;
padding: 4px 14px 14px;
border: 1px solid var(--line);
border-radius: 12px;
}
.card h2 {
margin-top: 12px;
}
.value {
font-weight: 600;
}
.row input {
flex: 1;
}
.sticky {
position: sticky;
top: 0;
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
padding: 8px 10px;
border-radius: 10px;
background: #1f1b3a;
color: #fff;
}
.filler li {
padding: 10px 0;
border-bottom: 1px solid var(--line);
}
wwwroot/js/scroll.js
Download file ↗// An ES module. Blazor loads it with import("./js/scroll.js")
// and holds it as an IJSObjectReference.
// Called from .NET with InvokeVoidAsync: nothing comes back.
export function scrollToTop() {
window.scrollTo({ top: 0, behavior: "smooth" });
}
// Reports the scroll position to a .NET object.
// dotNetRef is the DotNetObjectReference that C# passed in.
// Returns an object with stop(); .NET keeps it as another IJSObjectReference.
export function watchScroll(dotNetRef) {
let queued = false;
let active = true;
const onScroll = () => {
if (queued) return;
queued = true;
// At most one call into .NET per animation frame.
requestAnimationFrame(() => {
queued = false;
if (active) {
dotNetRef.invokeMethodAsync("OnScroll", Math.round(window.scrollY));
}
});
};
window.addEventListener("scroll", onScroll, { passive: true });
window.jsLab.listeners++;
return {
stop() {
if (!active) return;
active = false;
window.removeEventListener("scroll", onScroll);
window.jsLab.listeners--;
}
};
}
Expected result
After the first render, the first card shows the browser language and the window size, for example 'en-US · 390 × 844 px · touch: yes'. Saving a note shows 'localStorage has: <your note>'. Scrolling updates 'Scrolled N px · calls from JS: M' while you move, and Top scrolls back until the value is 0. The After dispose page shows 'Scroll listeners attached right now: 0' after every visit to Interop, because DisposeAsync stopped the listener.
The project runs in the SharpRune app and with the .NET 9 SDK. Open C# practice runs the separate portable exercise.
C# companion practice
using System;
using System.Collections.Generic;
using System.Text.Json;
// JS interop moves values as JSON. Blazor uses System.Text.Json with the web defaults.
var web = new JsonSerializerOptions(JsonSerializerDefaults.Web);
// 1. The object jsLab.browserInfo() returns, as JSON text, read into the same record as the page.
const string fromJs = """{"language":"en-US","width":390,"height":844,"touch":true}""";
var info = JsonSerializer.Deserialize<BrowserInfo>(fromJs, web)!;
Console.WriteLine(info);
// 2. Arguments travel as a JSON array, with camelCase names for objects.
object[] setItemArgs = ["jsbridge-note", "Buy milk"];
Console.WriteLine(JsonSerializer.Serialize(setItemArgs, web));
Console.WriteLine(JsonSerializer.Serialize(new BrowserInfo("uk-UA", 820, 1180, true), web));
// 3. A stand-in for the scroll listener: a source that calls back and can be stopped.
var page = new ScrollReceiver();
var window = new ScrollSource();
IDisposable watcher = window.Watch(page.OnScroll);
window.Scroll(120);
window.Scroll(480);
Console.WriteLine($"Watching: {page.Calls} calls, y = {page.Y}, listeners = {window.Listeners}");
watcher.Dispose();
window.Scroll(900);
Console.WriteLine($"After stop: {page.Calls} calls, y = {page.Y}, listeners = {window.Listeners}");
public sealed record BrowserInfo(string Language, int Width, int Height, bool Touch);
// Plays the part of the component with its [JSInvokable] OnScroll method.
public sealed class ScrollReceiver
{
public int Y { get; private set; }
public int Calls { get; private set; }
public void OnScroll(int y)
{
Y = y;
Calls++;
}
}
// Plays the part of window and js/scroll.js: it keeps callbacks until they are stopped.
public sealed class ScrollSource
{
private readonly List<Action<int>> callbacks = [];
public int Listeners => callbacks.Count;
public IDisposable Watch(Action<int> callback)
{
callbacks.Add(callback);
return new Stopper(() => callbacks.Remove(callback));
}
public void Scroll(int y)
{
foreach (var callback in callbacks.ToArray())
{
callback(y);
}
}
private sealed class Stopper(Action stop) : IDisposable
{
public void Dispose() => stop();
}
}
C# practice output
BrowserInfo { Language = en-US, Width = 390, Height = 844, Touch = True }
["jsbridge-note","Buy milk"]
{"language":"uk-UA","width":820,"height":1180,"touch":true}
Watching: 2 calls, y = 480, listeners = 1
After stop: 2 calls, y = 480, listeners = 0If a call fails because a function is not defined, check the identifier path from window and the module path, which is relative to the <base href>. Calls that need the page belong in OnAfterRenderAsync, not OnInitialized.