【问题标题】:Blazor unmarshalled javascript interop isolationBlazor 未编组的 javascript 互操作隔离
【发布时间】:2021-03-16 20:30:24
【问题描述】:

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);

【问题讨论】:

    标签: blazor blazor-webassembly


    【解决方案1】:

    到目前为止,还没有引用未编组的 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

    【讨论】:

    • 是的,这就是我正在使用的,只是不确定我是否没有遗漏什么,谢谢
    【解决方案2】:

    现在可以在 .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

    【讨论】:

      猜你喜欢
      • 2021-02-24
      • 1970-01-01
      • 2021-08-22
      • 2021-03-07
      • 2021-02-12
      • 1970-01-01
      • 2020-08-09
      • 2020-08-14
      • 2021-03-01
      相关资源
      最近更新 更多