Calling JavaScript from C# Code
Learn to use JavaScript interop to call JavaScript from C# code in Blazor.
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>
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
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.
Otherwise, it doesn’t matter whether the function is inserted directly ...
Ask