...

/

Calling JavaScript from C# Code

Calling JavaScript from C# Code

Learn to use JavaScript interop to call JavaScript from C# code in Blazor.

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. ...