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.
We'll cover the following...
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>
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
windowscope.It must be defined after the reference to the Blazor client library, which is
_framework/blazor.webassembly.jsin Blazor WebAssembly and_framework/blazor.server.jsin Blazor Server. ...