Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 41 ยท JS Interop and Auth

JS Modules and Calling .NET from JavaScript

Load JavaScript as isolated ES modules in Blazor, call C# from JavaScript with JSInvokable and DotNetObjectReference, and dispose references so nothing leaks.

Global window functions work for small experiments, but they pollute the global scope and any two scripts may collide on a name. Real apps use JavaScript modules that Blazor loads on demand. And one direction is often not enough: a map widget reports a click, a resize observer fires, a drag library finishes: JavaScript needs to call back into C#.

This lesson shows both ideas: isolated modules with IJSObjectReference, and calls from JavaScript to .NET with [JSInvokable] and DotNetObjectReference. The real code needs a browser and the framework, so it is read-only; two runnable stand-ins model the lifecycle (lazy module loading, callback registration and disposal) in plain C#.

JavaScript isolation with modules

Put the script in an ES module file next to the component, for example Components/Pages/Chart.razor.js, which the build publishes as a static web asset. A module exports functions:

JavaScript
// Chart.razor.js
export function drawBars(canvas, values) {
  const ctx = canvas.getContext("2d");
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  const width = canvas.width / values.length;
  values.forEach((v, i) => ctx.fillRect(i * width, canvas.height - v, width - 4, v));
}

export function version() {
  return "1.0";
}

In the component, import it with the built-in import function. You get an IJSObjectReference, a handle to the loaded module:

RAZOR
@implements IAsyncDisposable
@inject IJSRuntime JS

<canvas @ref="canvas" width="300" height="120"></canvas>

@code {
    private ElementReference canvas;
    private IJSObjectReference? module;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            module = await JS.InvokeAsync<IJSObjectReference>(
                "import", "./Components/Pages/Chart.razor.js");
            await module.InvokeVoidAsync("drawBars", canvas, new[] { 40, 80, 60, 100 });
        }
    }

    public async ValueTask DisposeAsync()
    {
        if (module is not null)
        {
            try { await module.DisposeAsync(); }
            catch (JSDisconnectedException) { /* the circuit is already gone */ }
        }
    }
}

Benefits of this approach:

  • No globals: the module's functions are only reachable through the reference you hold.
  • Lazy loading: the file downloads the first time a component imports it; the browser caches it afterwards.
  • Per-component scripts: a collocated .razor.js file is picked up automatically as a static asset.
  • Disposal: a reference to a JavaScript object holds memory on the JS side until you dispose it, so implement IAsyncDisposable.

Calling .NET from JavaScript

JavaScript can call:

  1. Static methods marked [JSInvokable]: DotNet.invokeMethodAsync("MyApp", "GetServerTime").
  2. Instance methods on an object you passed wrapped in DotNetObjectReference. This is the common choice, because the callback can touch the component's state.
RAZOR
@implements IDisposable
@inject IJSRuntime JS

<p>Window width: @width px</p>

@code {
    private int width;
    private DotNetObjectReference<Resizer>? selfRef;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            selfRef = DotNetObjectReference.Create(this);
            await JS.InvokeVoidAsync("observeWidth", selfRef);
        }
    }

    [JSInvokable]
    public async Task OnWidthChanged(int newWidth)
    {
        width = newWidth;
        await InvokeAsync(StateHasChanged);
    }

    public void Dispose() => selfRef?.Dispose();
}
JavaScript
window.observeWidth = (dotNetRef) => {
  const send = () => dotNetRef.invokeMethodAsync("OnWidthChanged", window.innerWidth);
  window.addEventListener("resize", send);
  send();
};

Details to remember:

  • A [JSInvokable] method must be public. You can rename it with [JSInvokable("widthChanged")].
  • Arguments and return values are serialized as JSON, like in the other direction.
  • JavaScript calls arrive outside a Blazor UI event, so call InvokeAsync(StateHasChanged) after you change state.
  • The DotNetObjectReference pins the .NET object in memory so JS can find it. Dispose it when the component goes away, and remove the JavaScript listener too, otherwise the browser keeps calling a disposed object and you get errors such as "There is no tracked object with id ...".
  • Do not pass a component's this directly: wrap it in DotNetObjectReference.Create(this).
sequenceDiagram
    participant C as C# component
    participant J as JavaScript
    C->>J: observeWidth(dotNetRef)
    J-->>J: add resize listener
    J->>C: dotNetRef.invokeMethodAsync("OnWidthChanged", 800)
    C-->>C: width = 800, StateHasChanged
    C->>J: dispose reference, remove listener

C# hands JavaScript a reference; JavaScript calls back through it until it is disposed.

Module loading in plain C#

The first stand-in captures the lifecycle: modules are loaded once per name, handed out as references, and become unusable after disposal.

C# Stand-in isolated JS modules

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.

Each import call returns a fresh reference to the shared, cached module, so disposing one does not break another component.

A callback registry you can run

The second stand-in models DotNetObjectReference: C# hands JavaScript an id, JavaScript calls back by id, and a disposed reference is rejected.

C# Stand-in DotNetObjectReference

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.

The two safety rules are visible: only methods marked [JSInvokable] can be called, and a disposed reference is gone.

Typical use cases

Task Pattern
Click on a third-party map Pass DotNetObjectReference, JS calls OnMapClick(lat, lng)
Detecting window resize or media queries Listener in a module, callback to C#, remove the listener on dispose
Drag-and-drop libraries Module initializes the library; callbacks report the drop
Download a file generated in C# DotNetStreamReference plus a small JS function creating a blob URL
Static utility needed by JS [JSInvokable] static method, call with DotNet.invokeMethodAsync

If JS needs to call C# very often (mouse move, scroll), throttle on the JavaScript side first. On Blazor Server every callback is a network message.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the advantage of importing a JavaScript module over a global window function?

    A module's exports are reachable only through the IJSObjectReference, and the file is loaded on demand.
  2. 2. What must a method have to be callable from JavaScript?

    Only public methods marked [JSInvokable] are exposed, either as static methods or on a DotNetObjectReference instance.
  3. 3. After JavaScript calls into your component, the UI does not update. Why?

    Callbacks do not trigger an automatic render, so call InvokeAsync(StateHasChanged).
  4. 4. Why dispose a DotNetObjectReference?

    The reference pins the object; leaving it undisposed leaks memory and lets JavaScript call a component that no longer exists.

Summary

  • Load scripts as ES modules with import and keep the IJSObjectReference; dispose it in DisposeAsync.
  • [JSInvokable] plus DotNetObjectReference lets JavaScript call C# instance methods.
  • Callbacks run outside UI events, so re-render with InvokeAsync(StateHasChanged).
  • Dispose references and remove JavaScript listeners when a component is removed.
  • Throttle chatty callbacks, especially on Blazor Server.

Next: Authentication and Authorization