Blazor Web Assembly PWA - 安装对话框

Min*_*wky 3 progressive-web-apps blazor blazor-webassembly

Blazor Web Assembly PWA 中有没有办法添加“安装”对话框提示?类似于 Youtube Music 的东西

Mis*_*goo 5

粗略的流程是

  • 为.....注册beforeinstallprompt
  • 当该事件触发时,存储该事件以供以后使用(听起来很奇怪,但您需要它)
  • 调用 Blazor 以显示提示警报
  • 回调 JS 并使用隐藏事件启动安装过程

注册安装提示通知

window.addEventListener('beforeinstallprompt', function (e) {
    e.preventDefault();
    // Stash the event so it can be triggered later.
    // where you store it is up to you
    window.PWADeferredPrompt = e;
    // Notify C# Code that it can show an alert 
    // MyBlazorInstallMethod must be [JSInvokable]
    DotNet.invokeMethodAsync("MyBlazorAssembly", "MyBlazorInstallMethod");
});
Run Code Online (Sandbox Code Playgroud)

然后,此 C# 方法可以显示一条警报,告知用户可以安装为桌面应用程序并提供“安装/取消”按钮。

注册一个可以从 Blazor/C# 调用的 JS 函数

window.BlazorPWA = {
    installPWA: function () {
        if (window.PWADeferredPrompt) {
            // Use the stashed event to continue the install process
            window.PWADeferredPrompt.prompt();
            window.PWADeferredPrompt.userChoice
                .then(function (choiceResult) {
                    window.PWADeferredPrompt = null;
                });
        }
    }
};
Run Code Online (Sandbox Code Playgroud)

Blazor 代码

[JSInvokable]
public async Task MyBlazorInstallMethod()
{
  // show an alert and get the result
  ...
  // tell browser to install
  if (UserChoseInstall)
  {
    await jSRuntime.InvokeVoidAsync("BlazorPWA.installPWA");
  }
}
Run Code Online (Sandbox Code Playgroud)