Blazor Web Assembly PWA 有没有办法添加“安装”对话框提示?类似于 Youtube 音乐的东西
答案 0 :(得分:1)
粗略的流程是
beforeinstallprompt
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");
});
然后,此 C# 方法可以显示警告,提示用户可以将其安装为桌面应用并提供安装/取消按钮。
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;
});
}
}
};
[JSInvokable]
public async Task MyBlazorInstallMethod()
{
// show an alert and get the result
...
// tell browser to install
if (UserChoseInstall)
{
await jSRuntime.InvokeVoidAsync("BlazorPWA.installPWA");
}
}