Search⌘ K
AI Features

Calling JavaScript from C# Code

Explore how to call JavaScript functions from C# code within Blazor components by using the IJSRuntime interface. Understand the requirements for defining callable JavaScript functions and how to invoke them asynchronously, with or without return values, to enhance your web application's interactivity.

In Blazor, we can invoke JavaScript functions from compiled C# code. Here, we have an example of a JavaScript function that is callable from Blazor code, and we also have some code that calls it.

<Router AppAssembly="@typeof(App).Assembly">
    <Found Context="routeData">
        <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
        <FocusOnNavigate RouteData="@routeData" Selector="h1" />
    </Found>
    <NotFound>
        <PageTitle>Not found</PageTitle>
        <LayoutView Layout="@typeof(MainLayout)">
            <p role="alert">Sorry, there's nothing at this address.</p>
        </LayoutView>
    </NotFound>
</Router>
A Blazor project setup with JavaScript interop

Defining a callable JavaScript function

We cannot just invoke any JavaScript function from Blazor. The function must fulfill the following criteria:

  • It must be defined at the window scope.

  • It must be defined after the reference to the Blazor client library, which is _framework/blazor.webassembly.js in Blazor WebAssembly and _framework/blazor.server.js in Blazor Server. ...