Is there a way in Blazor Web Assembly PWA to add an "Install" dialog prompt? Something similar to Youtube Music
1
-
docs.microsoft.com/en-us/aspnet/core/blazor/… – jmoerdyk Feb 18 at 17:15
Add a comment
|
The rough flow is
- Register for
beforeinstallprompt
- When that event fires, store the event for later (sounds odd but you need it)
- Call into Blazor to display a prompt alert
- Call back to JS and use the stashed event to start the install process
Register for install prompt notification
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");
});
This C# method can then display an alert to say the user can install as a desktop app and offer Install/Cancel buttons.
Register a JS function you can call from Blazor/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;
});
}
}
};
Blazor code
[JSInvokable]
public async Task MyBlazorInstallMethod()
{
// show an alert and get the result
...
// tell browser to install
if (UserChoseInstall)
{
await jSRuntime.InvokeVoidAsync("BlazorPWA.installPWA");
}
}