I'm working on a Blazor Server 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:
- If I open DevTools and run
showAlert("Hello from console!"), it works — so the script is properly loaded. - The script shows under
Sourcesin the browser. - No errors appear in the browser console.
- Blazor server is running fine otherwise.
What Doesn't Work:
- Clicking buttons with
@onclick="..."and callingJS.InvokeVoidAsync(...)does nothing. - Calling JS from
OnAfterRenderAsyncalso does nothing — no alert is shown. - I do not see any console logs from
Console.WriteLine()server-side either.
Any help would be appreciated