Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

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

$
0
0

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 Sources in the browser.
  • No errors appear in the browser console.
  • Blazor server is running fine otherwise.

What Doesn't Work:

  • Clicking buttons with @onclick="..." and calling JS.InvokeVoidAsync(...) does nothing.
  • Calling JS from OnAfterRenderAsync also does nothing — no alert is shown.
  • I do not see any console logs from Console.WriteLine() server-side either.

Any help would be appreciated


Viewing all articles
Browse latest Browse all 4839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>