Blazor 解组 javascript 互操作隔离

Blazor unmarshalled javascript interop isolation

Blazor 具有 javascript 隔离,如下所示:

var module = await js.InvokeAsync<IJSObjectReference>("import",./_content/MyComponents/exampleJsInterop.js");
await module.InvokeAsync<string>("showPrompt", message);

是否可以将其与未编组的调用结合使用?我想做这样的事情:

var module = await js.InvokeUnmarshalled<IJSUnmarshalledObjectReference>("import",./_content/MyComponents/exampleJsInterop.js");
await module.InvokeUnmarshalled<string>("showPrompt", message);

到今天为止,还没有引用未编组的 JS 模块的解决方案,但是您可以这样做来检查 IJSUnmarshalledRuntime 是否可用:

// Check if the IJSRuntime is the WebAssembly implementation of the JSRuntime
if (JsRuntime is IJSUnmarshalledRuntime wasmJsRuntime)
{
    wasmJsRuntime.InvokeUnmarshalled<string, string, byte[], bool>("Download", fileName, contentType, file);
}
else
{
    // Fall back to the slow method if not in WebAssembly
    await DownloadModule.InvokeVoidAsync("Download", fileName, contentType, file);
}

有关使用 IJSUnmarshalledRuntime 的更多信息,请点击此处:https://docs.microsoft.com/en-us/aspnet/core/blazor/call-javascript-from-dotnet?view=aspnetcore-5.0#unmarshalled-js-interop

现在可以在 .Net 6 中实现。 此处讨论了更改 Github discussion

您现在可以使用强制转换作为您的模块参考:

var module = await js.InvokeAsync<IJSObjectReference>("import",./_content/MyComponents/exampleJsInterop.js");
if(module is IJSUnmarshalledObjectReference objRef)
{
    objRef.InvokeUnmarshalled<string, string, byte[], bool>("Download", fileName, contentType, file);
}

使用 .Net 5 可以使用反射来调用一些内部函数。这些模块只有一个附加参数:long targetInstanceId。在我的项目中,这些 id 以 1 开头,并随着每个导入的模块递增 1。 Source