blazorblazor-server-sideblazor-jsinteropasp.net-core-9.0

Blazor Server JS Interop Not Triggering in OnAfterRenderAsync Despite JS Loaded and Working in Console


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

What doesn't work

Any help would be appreciated.


Solution

  • try this

        <Routes @rendermode="InteractiveServer"/>