Course contentsShow
← C#
Lesson 1329 of 1,90812. Modern Frontend with Razor and BlazorFree lesson

Working with Blazor JS Interop

Invoke native JavaScript functions from C# to access browser-specific capabilities.

In this lesson, you will learn how to bridge the gap between your C# Blazor code and the browser’s native JavaScript environment to access hardware or browser-specific capabilities.

The Bridge Between Worlds

While Blazor allows you to build sophisticated web applications using C#, some browser features—like accessing the Geolocation API, manipulating the browser's local storage, or interacting with specific third-party JavaScript libraries—are only exposed through native JavaScript. Blazor JS Interop provides a secure "bridge" that allows your C# code to invoke functions in the browser’s global window scope.

Invoking JavaScript from C#

To call a JavaScript function, you must inject the IJSRuntime service into your component. This service acts as the orchestrator for all interop calls.

Imagine you want to trigger a simple browser alert. First, define the JavaScript function in your wwwroot/index.html (or _Host.cshtml):

window.showAlert = (message) => {
    alert(message);
};

Now, in your Razor component, you can call this function using InvokeVoidAsync (if you don’t need a return value) or InvokeAsync<T> (if you expect data back from JavaScript):

@inject IJSRuntime JS

<button @onclick="TriggerAlert">Click Me</button>

@code {
    private async Task TriggerAlert()
    {
        // "showAlert" matches the name on the window object
        await JS.InvokeVoidAsync("showAlert", "Hello from C#!");
    }
}

Why it Matters

The InvokeAsync methods are inherently asynchronous because the communication between the Blazor runtime and the browser's JavaScript engine happens over a serialized connection. By using this pattern, you keep your business logic in C# while safely "borrowing" the specialized functionality of the web platform when necessary. Whether you are measuring the dimensions of an HTML element or triggering a native browser notification, JS Interop ensures that your C# application remains a first-class citizen in the browser.

Key Takeaway: Use the IJSRuntime service and the InvokeAsync methods to execute JavaScript functions from your C# code, enabling your Blazor components to reach beyond the managed runtime and interact directly with browser APIs.