监听 beforeinstallprompt 事件
当浏览器触发 beforeinstallprompt
事件时,表示 Web 应用可以安装,并且可以向用户显示安装按钮。当应用满足可安装性条件时,系统会触发 beforeinstallprompt
事件。
捕获该事件可让开发者自定义安装,并在他们认为最合适的时间提示用户安装。
- 点击 Remix to Edit 使项目可供修改。
- 向
window
对象添加beforeinstallprompt
事件处理脚本。 - 将
event
保存为全局变量;我们稍后需要使用它来显示提示。 - 取消隐藏“安装”按钮。
代码:
window.addEventListener('beforeinstallprompt', (event) => {
// Prevent the mini-infobar from appearing on mobile.
event.preventDefault();
console.log('👍', 'beforeinstallprompt', event);
// Stash the event so it can be triggered later.
window.deferredPrompt = event;
// Remove the 'hidden' class from the install button container.
divInstall.classList.toggle('hidden', false);
});
处理安装按钮点击事件
如需显示安装提示,请对已保存的 beforeinstallprompt
事件调用 prompt()
。在安装按钮点击处理程序中调用 prompt()
,因为 prompt()
必须通过用户手势调用。
- 为安装按钮添加点击事件处理脚本。
- 对已保存的
beforeinstallprompt
事件调用prompt()
。 - 记录提示的结果。
- 将已保存的
beforeinstallprompt
事件设为 null。 - 隐藏“安装”按钮。
代码:
butInstall.addEventListener('click', async () => {
console.log('👍', 'butInstall-clicked');
const promptEvent = window.deferredPrompt;
if (!promptEvent) {
// The deferred prompt isn't available.
return;
}
// Show the install prompt.
promptEvent.prompt();
// Log the result
const result = await promptEvent.userChoice;
console.log('👍', 'userChoice', result);
// Reset the deferred prompt variable, since
// prompt() can only be called once.
window.deferredPrompt = null;
// Hide the install button.
divInstall.classList.toggle('hidden', true);
});
跟踪安装事件
通过安装按钮安装 Web 应用只是用户安装 Web 应用的一种方式。他们还可以通过 Chrome 的菜单、迷你信息栏和多功能框中的图标来使用该功能。您可以通过监听 appinstalled
事件来跟踪所有这些安装方式。
- 向
window
对象添加appinstalled
事件处理脚本。 - 将安装事件记录到分析或其他机制。
代码:
window.addEventListener('appinstalled', (event) => {
console.log('👍', 'appinstalled', event);
// Clear the deferredPrompt so it can be garbage collected
window.deferredPrompt = null;
});
深入阅读
恭喜,您的应用现在可以安装了!
您还可以执行以下操作: