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

How do I run JavaScript in .NET 8 Blazor Web App?

$
0
0

My code was a bit more complex but I cut it down to the most simple use case to simplify the problem: "Show an alert box with a message"

I can make it work in .NET 7 Blazor Server but the exact same thing does not work in .NET Blazor Web App.

What did I try:

.NET 7 Blazor Server:

I create a new app with the Blazor server template.

I create a new nav item, same as the existing ones: Shared/NavMenu.razor.

<div class="nav-item px-3"><NavLink class="nav-link" href="component"><span class="oi oi-list-rich" aria-hidden="true"></span> Component</NavLink></div>

Then I add a Blazor Component: Pages/Component.razor

@page "/component"@inject IJSRuntime JSRuntime<button @onclick=ButtonClicked>Perform interop</button>@code{    private async Task ButtonClicked()    {        await JSRuntime.InvokeVoidAsync("console.log", "Button event fired");        await JSRuntime.InvokeVoidAsync("alert", "Hello world");    }}

The alert box is displayed when I click the button and is logged to the browser console.

Browser console in developer tools:

[2024-04-11T08:04:30.710Z] Information: Normalizing '_blazor' to 'https://localhost:7004/_blazor'. blazor.server.js:1[2024-04-11T08:04:30.736Z] Information: WebSocket connected to wss://localhost:7004/_blazor?id=_4uKQ. blazor.server.js:1Button event fired blazor.server.js:1

.NET 8 Blazor Web App

I create a new app with Blazor Web App template:

Interactive render mode: Server

Interactivity location: Per page/component

I create a new nav item, same as the existing ones, in Components/Layout/NavMenu.razor (same as above).

I add a Blazor Component: Components/Pages/Component.razor

@page "/component"@inject IJSRuntime JSRuntime<button @onclick="ButtonClicked">Perform interop</button>@code{    private async Task ButtonClicked()    {        await JSRuntime.InvokeVoidAsync("console.log", "Button event fired");        await JSRuntime.InvokeVoidAsync("alert", "Hello world");    }}

The button is there but nothing happens when I click on it. No 'alert' and the the browser console is empty and nothing is logged to the console.

Edit: added code from .NET 8 Blazor Web App


Viewing all articles
Browse latest Browse all 4839

Trending Articles



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