Introduction

Blazor lets developers build modern web applications using C#. However, some browser features and third-party libraries are only available through JavaScript.

JavaScript Interop (JS Interop) bridges this gap by allowing Blazor and JavaScript to communicate with each other.

Whether you need to display a Chart.js graph, access browser storage, manipulate the DOM, download files, or call browser APIs, JS Interop is the recommended solution.

This guide explains how JavaScript Interop works in Blazor with practical examples and common troubleshooting tips.


What is JavaScript Interop?

Blazor applications run primarily in C#, while browsers execute JavaScript.

JS Interop enables communication in both directions:

Blazor (C#)
      │
      â–ŧ
 JavaScript

JavaScript
      │
      â–ŧ
 Blazor (.NET)

You can:


Calling JavaScript from Blazor

Inject IJSRuntime:

@inject IJSRuntime JS

Call a JavaScript function:

await JS.InvokeVoidAsync("showMessage");

JavaScript:

window.showMessage = function () {
    alert("Hello from JavaScript!");
};

Returning Values from JavaScript

JavaScript:

window.getBrowserWidth = function () {
    return window.innerWidth;
}

Blazor:

int width = await JS.InvokeAsync<int>("getBrowserWidth");

Passing Parameters

JavaScript:

window.showName = function(name){
    alert(name);
}

Blazor:

await JS.InvokeVoidAsync("showName","Algolassi");

Calling JavaScript After Rendering

One of the most common mistakes is calling JavaScript before the page has finished rendering.

Correct approach:

protected override async Task OnAfterRenderAsync(bool firstRender)
{
    if (firstRender)
    {
        await JS.InvokeVoidAsync("initializeChart");
    }
}

Using JavaScript Modules

Instead of placing every function inside window, Blazor supports JavaScript modules.

module = await JS.InvokeAsync<IJSObjectReference>(
    "import",
    "./js/site.js");

Call a function:

await module.InvokeVoidAsync("showToast");

Advantages:


Calling Blazor from JavaScript

Decorate the C# method:

[JSInvokable]
public static string GetVersion()
{
    return "Version 1.0";
}

JavaScript:

DotNet.invokeMethodAsync(
    "YourProject",
    "GetVersion")
.then(result => console.log(result));

Calling Instance Methods

DotNetObjectReference.Create(this)

JavaScript can invoke methods on that specific object.

This is useful for:


Working with Browser Local Storage

Save:

localStorage.setItem("username","John");

Read:

return localStorage.getItem("username");

Blazor:

string user =
await JS.InvokeAsync<string>("getUser");

Integrating Third-Party JavaScript Libraries

JS Interop allows Blazor to work with libraries such as:

Example:

Blazor

↓

JavaScript Wrapper

↓

Chart.js

↓

Browser

Common JavaScript Interop Errors

1. Function Not Found

Could not find 'showMessage'

Solution:

Ensure the JavaScript file is loaded before calling the function.


2. JSDisconnectedException

Occurs when:

Handle gracefully:

try
{
    await JS.InvokeVoidAsync("showMessage");
}
catch(JSDisconnectedException)
{
}

3. JavaScript Before Render

Wrong:

OnInitializedAsync()

Correct:

OnAfterRenderAsync()

4. Module Import Error

Failed to fetch dynamically imported module

Usually caused by:


5. Cannot Create a JSObjectReference from the Value Null

This happens when a JavaScript function returns null but Blazor expects a JavaScript object reference.

Example:

IJSObjectReference module =
await JS.InvokeAsync<IJSObjectReference>("import", "./js/site.js");

Check that the module path is correct and the file is included in your published application.


Best Practices


Real-World Use Cases

JavaScript Interop is commonly used for:


Conclusion

JavaScript Interop is an essential part of Blazor development. It enables your application to interact with browser features and JavaScript libraries while keeping most of your application logic in C#. By understanding when and how to use JS Interop, you can build richer and more interactive Blazor applications.


Frequently Asked Questions

What is JavaScript Interop in Blazor?

JavaScript Interop allows Blazor applications to call JavaScript functions and lets JavaScript invoke .NET methods, enabling access to browser APIs and third-party libraries.

When should I use OnAfterRenderAsync for JS Interop?

Use OnAfterRenderAsync when the JavaScript code depends on rendered HTML elements, such as initializing charts or manipulating the DOM.

Can Blazor use JavaScript libraries like Chart.js?

Yes. Blazor integrates with JavaScript libraries such as Chart.js, ECharts, Plotly, Monaco Editor, and many others through JavaScript Interop.

What causes the "Could not find" JavaScript function error?

This usually happens when the JavaScript file isn't loaded, the function name is incorrect, or the script is referenced after the Blazor application starts.

🤖 AlgoLassi Assistant Have a question about this tutorial?

Ask AlgoLassi and get an answer plus the tutorials worth studying next.

Ask a question

đŸ’Ŧ Comments

Sign in with Google to publish immediately, or comment anonymously and wait for approval.

Comments will appear here when available.