I'm working on a Blazor Server on .NET 9.0 application and trying to integrate basic JavaScript interop before adding external libraries like Algolia InstantSearch.
This is my current code setup - interop.js
:
window.showAlert = function (message) {
alert(message);
};
App.razor
:
<body>
<Routes />
<script src="_framework/blazor.web.js"></script>
<script src="_framework/blazor.server.js"></script>
<script src="js/interop.js"></script>
</body>
interop.razor
:
@page "/interop"
@inject IJSRuntime JS
<h3>JavaScript Interop Test</h3>
<p>This page runs JavaScript when the component finishes rendering.</p>
@code {
private bool _firstRender = true;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
Console.WriteLine("Component rendered. Running JS interop...");
await JS.InvokeVoidAsync("showAlert", "JS Interop triggered on render!");
}
}
}
Program.cs
:
var services = builder.Services;
services.AddRazorComponents().AddInteractiveServerComponents();
Routes.razor
:
<Router AppAssembly="typeof(Program).Assembly">
<Found Context="routeData">
<RouteView RouteData="routeData" DefaultLayout="@typeof(Layout.MainLayout)" />
<FocusOnNavigate RouteData="routeData" Selector="h1" />
</Found>
</Router>
What works
showAlert("Hello from console!")
, it works — so the script is properly loaded.Sources
in the browser.What doesn't work
@onclick="..."
and calling JS.InvokeVoidAsync(...)
does nothing.OnAfterRenderAsync
also does nothing — no alert is shown.Console.WriteLine()
server-side either.Any help would be appreciated.
try this
<Routes @rendermode="InteractiveServer"/>