Learn Blazor · 11/15

JavaScript Interoperability (JS Interop)

6 min read

👋 Introduction

Welcome back, developer! So, you chose Blazor because you love C# and—let's be honest—you probably have a mild-to-severe allergy to writing complex JavaScript. You were promised a utopia where .razor files float on clouds of pure .NET.

But then, reality hits. You need to use a specific payment gateway widget that only has a JS SDK. Or maybe you need to render a fancy chart, and Chart.js is looking really good. Or perhaps you just want to set focus on an input field, and C# is looking at the browser DOM like a dog looking at a ceiling fan—confused and unable to reach it.

Definition: JavaScript Interoperability (JS Interop) is a mechanism in Blazor that allows C# code to call JavaScript code and vice-versa.

It acts as a bridge. Imagine two people who speak different languages (C# and JS) sitting in separate glass rooms. JS Interop is the phone line connecting them, translating the messages (JSON) back and forth.


1. The 'Why': When to use JavaScript in a C# App

The Problem

Blazor WebAssembly runs inside the browser's WebAssembly sandbox. Blazor Server runs on the server and talks to the browser via SignalR. In both cases, C# does not have direct access to the browser's DOM (Document Object Model) or Web APIs (like Geolocation, LocalStorage, or Canvas) in the same native way JavaScript does.

The Solution

We use JS Interop to access these capabilities. However, with great power comes great responsibility (and potential performance costs).

🚦 When to use it?

Don't use JS Interop for simple UI logic (like toggling a button class)—Blazor handles that natively. Use it for:

  1. Existing Libraries: You want to use mature JS libraries like D3.js, Leaflet (Maps), or Chart.js.
  2. Browser APIs: Accessing localStorage, sessionStorage, geolocation, or clipboard access (though many community packages like Blazored wrap these for you, it's good to know how they work).
  3. DOM Manipulation: Calculating the exact width of an element or setting focus (though ElementReference handles focus often, sometimes you need more control).

Did you know? 🧠
Every time you call JS from Blazor, the arguments are serialized into JSON, sent over the bridge, and deserialized. On Blazor Server, this travels over the network! So, calling a JS function 1,000 times in a loop is a great way to make your app run like a potato. 🥔


2. Calling JavaScript Functions from .NET Code

To talk to JavaScript, we need an abstraction called IJSRuntime.

Step 1: define the JavaScript

First, let's create a simple JavaScript function. In a standard Blazor app, you would put this in your wwwroot/index.html (Wasm) or Pages/_Layout.cshtml / Pages/_Host.cshtml (Server), usually inside the <body> tag.

html
<script>
    window.myCustomFunctions = {
        showAlert: function (message) {
            alert(message);
        },
        calculateSum: function (a, b) {
            return a + b;
        }
    };
</script>

Step 2: Inject IJSRuntime

Inside your Razor component (.razor), you need to ask Blazor to give you the phone line.

csharp
@page "/js-interop-demo"
@inject IJSRuntime JSRuntime

<button class="btn btn-primary" @onclick="TriggerAlert">
    Say Hello via JS
</button>

<p>Sum result: @result</p>
<button class="btn btn-secondary" @onclick="Calculate">
    Calculate 10 + 20
</button>

@code {
    private int result;

    private async Task TriggerAlert()
    {
        // InvokeVoidAsync is used when JS function returns nothing
        await JSRuntime.InvokeVoidAsync("myCustomFunctions.showAlert", "Hello from C#!");
    }

    private async Task Calculate()
    {
        // InvokeAsync<T> is used when we expect a return value
        result = await JSRuntime.InvokeAsync<int>("myCustomFunctions.calculateSum", 10, 20);
    }
}

🔍 Under the Hood

  1. Dependency Injection: @inject IJSRuntime brings the service in.
  2. Async/Await: Notice we use InvokeAsync? Always prefer the Async versions. Even in WebAssembly where JS is technically synchronous, keeping it async allows your code to work on Blazor Server (where the call must wait for a network roundtrip).
  3. Serialization: The integer 10 and 20 are turned into JSON strings, sent to the browser, parsed by JS, added together, and the result is sent back.

3. Calling .NET Methods from JavaScript

Sometimes, JavaScript needs to tell C# that something happened. For example, maybe a Google Map marker was clicked (JS event) and you want to load customer data from your C# database.

The Problem

JavaScript doesn't know your C# classes exist. It relies on the DotNet global object provided by Blazor.

The Solution

We pass a "Reference" of our C# object to JavaScript.

Scenario: The Instance Method Call

This is the most common industry standard. We want a specific component instance to receive the call.

1. The C# Component:

csharp
@page "/call-dotnet"
@inject IJSRuntime JSRuntime
@implements IDisposable

<h3>Current Count from JS: @count</h3>

<button @onclick="StartTimer">Start JS Timer</button>

@code {
    private int count = 0;
    // We need to hold a reference to 'this' component
    private DotNetObjectReference<CallDotNet>? objRef;

    private async Task StartTimer()
    {
        // Create a reference to this specific instance of the component
        objRef = DotNetObjectReference.Create(this);
        
        // Pass the reference to JS
        await JSRuntime.InvokeVoidAsync("timerHelper.start", objRef);
    }

    // [JSInvokable] makes this method visible to JavaScript
    [JSInvokable] 
    public void UpdateCount()
    {
        count++;
        // Important: Tell Blazor the state changed because this was triggered externally!
        StateHasChanged(); 
    }

    public void Dispose()
    {
        // ⚠️ CRITICAL: Always dispose the reference to prevent memory leaks!
        objRef?.Dispose();
    }
}

2. The JavaScript:

javascript
window.timerHelper = {
    start: function (dotnetHelper) {
        setInterval(() => {
            // Call the C# method 'UpdateCount'
            dotnetHelper.invokeMethodAsync('UpdateCount'); 
        }, 1000);
    }
};

🎩 Industry Practice Note

Notice the StateHasChanged()? When JS triggers a C# method, Blazor's rendering engine might not know it needs to refresh the UI. You often have to nudge it manually.

Also, Memory Management: If you create a DotNetObjectReference, you create a strong reference. If you don't Dispose() it, that component will stay in memory forever, like a ghost haunting your server's RAM. 👻


4. Isolating JavaScript Modules per Component

The Problem: Global Pollution

In the examples above, we wrote window.myCustomFunctions. If you have a massive app, dumping everything into window is messy. What if two components both want a function named init? They will overwrite each other. Chaos ensues. 🔥

The Solution: JS Isolation (ES Modules)

Blazor allows you to load JavaScript files specifically for one component. These files are not global; they are modules.

How to do it

  1. Create a JS file in wwwroot/js/ (or right next to your component if using CSS isolation logic, though wwwroot is cleaner for JS). Let's call it myModule.js.

wwwroot/js/myModule.js

javascript
// notice the 'export' keyword. This is an ES Module.
export function showPrompt(message) {
    return prompt(message, 'Type something');
}
  1. Import it in the Component.

MyComponent.razor

csharp
@inject IJSRuntime JSRuntime
@implements IAsyncDisposable

<button @onclick="TriggerPrompt">Prompt Me</button>
<p>You typed: @userMessage</p>

@code {
    // We store the module reference, not just the runtime
    private IJSObjectReference? module;
    private string? userMessage;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            // Dynamic Import! loads the file only when needed
            module = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./js/myModule.js");
        }
    }

    private async Task TriggerPrompt()
    {
        if (module is not null)
        {
            // Call the function ON THE MODULE, not globally
            userMessage = await module.InvokeAsync<string>("showPrompt", "What is your quest?");
        }
    }

    async ValueTask IAsyncDisposable.DisposeAsync()
    {
        if (module is not null)
        {
            await module.DisposeAsync();
        }
    }
}

Why is this the Industry Standard?

  1. Lazy Loading: The JS file isn't downloaded until the user actually visits that page. Saves bandwidth!
  2. No Conflicts: You can have init() in 50 different files; they won't clash because they are scoped to the module variable.
  3. Maintainability: JS logic lives in a separate .js file, not mixed inside .cshtml or .html strings.

📚 References & Further Reading

Challenge

Challenge: Create a Persistent User Greeting Component

Your task is to build a Blazor component named UserPersistence that saves a user's name to the browser's localStorage and retrieves it upon subsequent visits. This requires a combination of C# and JavaScript, leveraging Blazor's JS isolation feature for maintainability and to avoid polluting the global namespace.

C# Component (UserPersistence.razor) Requirements:

  1. Inject IJSRuntime: Make the JavaScript runtime available to the component.
  2. Implement IAsyncDisposable: Ensure that JavaScript resources are properly released to prevent memory leaks.
  3. Dynamic Module Import: In the appropriate lifecycle method (OnAfterRenderAsync is recommended for initial JS interop), dynamically import the JavaScript module located at ./js/storage.js. Store the resulting IJSObjectReference in a private field.
  4. Load on Init: After importing the module, immediately call a method to load the user's name from localStorage.
  5. Save Method: Create a public async Task method SaveNameToStorageAsync(string name) that invokes the save function from your JavaScript module, passing 'userName' as the key and the provided name as the value.
  6. Load Method: Create a public async Task method LoadNameFromStorageAsync() that invokes the get function from your JavaScript module with the key 'userName' and updates the component's state with the retrieved name.
  7. Resource Cleanup: Correctly implement the DisposeAsync method to dispose of the IJSObjectReference when the component is destroyed.

JavaScript Module (wwwroot/js/storage.js) Requirements:

  1. ES Module: The file must be structured as a standard JavaScript ES Module.
  2. save Function: Export a function named save that accepts two arguments, key and value, and uses them to call localStorage.setItem().
  3. get Function: Export a function named get that accepts a key argument and returns the result of localStorage.getItem(key).

Expected result

Your final code should consist of a completed Blazor component and a JavaScript ES module. The two parts should work together to read from and write to the browser's localStorage.

UserPersistence.razor

csharp
@implements IAsyncDisposable
@inject IJSRuntime JSRuntime

<h3>User Persistence</h3>
<p>Welcome back, <strong>@UserName</strong>!</p>
<input @bind="currentName" placeholder="Enter your name" />
<button @onclick="() => SaveNameToStorageAsync(currentName)">Save Name</button>

@code {
    private string? UserName { get; set; } = "Guest";
    private string? currentName;
    private IJSObjectReference? _storageModule;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            _storageModule = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./js/storage.js");
            await LoadNameFromStorageAsync();
            StateHasChanged();
        }
    }

    public async Task SaveNameToStorageAsync(string name)
    {
        if (_storageModule is not null && !string.IsNullOrWhiteSpace(name))
        {
            await _storageModule.InvokeVoidAsync("save", "userName", name);
            UserName = name;
            currentName = string.Empty;
        }
    }

    public async Task LoadNameFromStorageAsync()
    {
        if (_storageModule is not null)
        {
            var storedName = await _storageModule.InvokeAsync<string>("get", "userName");
            if (!string.IsNullOrEmpty(storedName))
            {
                UserName = storedName;
            }
        }
    }

    async ValueTask IAsyncDisposable.DisposeAsync()
    {
        if (_storageModule is not null)
        {
            await _storageModule.DisposeAsync();
        }
    }
}

wwwroot/js/storage.js

javascript
export function save(key, value) {
    window.localStorage.setItem(key, value);
}

export function get(key) {
    return window.localStorage.getItem(key);
}
csharp

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.