Mac上Blazor WASM调用JS遇System.Runtime.InteropServices.JS平台不支持错误
Blazor WASM调用JS函数抛出PlatformNotSupportedException错误
在搭载Sonoma 14.3系统的Intel版MacBook上运行.NET 8.0,尝试在Blazor WASM客户端项目中调用JavaScript函数,编写了alert测试代码,但执行时抛出异常,提示System.Runtime.InteropServices.JavaScript is not supported on this platform。
代码实现
NetToJsWasm.razor
@namespace SharedComponents.JSInteropSamples @page "/nettojswasm" @rendermode InteractiveWebAssembly @using System.Runtime.InteropServices.JavaScript <h3>This is a demo how to call JavaScript from .NET</h3> <button @onclick="ShowMyAlert">Show Alert</button> @code { protected async void ShowMyAlert() { ShowAlert("Hello from .NET"); } protected override async Task OnInitializedAsync() { await JSHost.ImportAsync("nettojswasm", "NetToJSWasm.razor.js"); } }
NetToJsWasm.razor.js
export function showAlert(message) { return alert(message); }
NetToJsWasm.razor.cs
namespace SharedComponents.JSInteropSamples; using System.Runtime.InteropServices.JavaScript; public partial class NetToJsWasm { [JSImport("showAlert", "nettojswasm")] internal static partial string ShowAlert(string message); }
错误信息
PlatformNotSupportedException: System.Runtime.InteropServices.JavaScript is not supported on this platform. System.Runtime.InteropServices.JavaScript.JSHost.ImportAsync(string moduleName, string moduleUrl, CancellationToken cancellationToken) MyBlog.Client.JSInteropSamples.NetToJsWasm.OnInitializedAsync() in NetToJsWasm.razor + await JSHost.ImportAsync("nettojswasm", "NetToJSWasm.razor.js"); Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync() ...
解决方法
方法一:限制代码仅在浏览器环境执行
JSHost和[JSImport]仅支持Blazor WASM的浏览器运行时,若组件存在服务器端预渲染逻辑,会导致服务器执行时抛出异常。可通过环境判断规避:
修改NetToJsWasm.razor中的代码:
@code { protected async void ShowMyAlert() { if (OperatingSystem.IsBrowser()) { ShowAlert("Hello from .NET"); } } protected override async Task OnInitializedAsync() { if (OperatingSystem.IsBrowser()) { await JSHost.ImportAsync("nettojswasm", "NetToJSWasm.razor.js"); } } }
方法二:改用Blazor标准IJSRuntime调用方式
这是兼容性更强的通用方案,避免平台支持问题:
- 修改
NetToJsWasm.razor,注入IJSRuntime并调整调用逻辑:
@namespace SharedComponents.JSInteropSamples @page "/nettojswasm" @rendermode InteractiveWebAssembly @inject IJSRuntime JS <h3>This is a demo how to call JavaScript from .NET</h3> <button @onclick="ShowMyAlert">Show Alert</button> @code { protected async Task ShowMyAlert() { await JS.InvokeVoidAsync("showAlert", "Hello from .NET"); } }
- 修改
NetToJsWasm.razor.js,将函数挂载到全局window对象:
window.showAlert = function(message) { alert(message); }
删除
NetToJsWasm.razor.cs文件,无需再使用[JSImport]特性。在
NetToJsWasm.razor末尾添加脚本引用(Blazor 8+支持组件级脚本):
<script src="./NetToJsWasm.razor.js"></script>
方法三:检查项目目标框架配置
确保Blazor WASM客户端项目的.csproj中目标框架设置为net8.0-browser:
<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly"> <PropertyGroup> <TargetFramework>net8.0-browser</TargetFramework> <Nullable>enable</Nullable> <ImplicitUsings>enable</ImplicitUsings> </PropertyGroup> </Project>
内容的提问来源于stack exchange,提问作者Sourcerer
相关产品推荐
相关产品推荐

