我正在尝试在我的渐进式网络应用程序上创建一个“添加到主屏幕”按钮,如 Chrome's documentation 中所述.
我通常遵循规定的模式,我有一些隐藏按钮,当 Chrome 的 beforeinstallprompt
事件触发时显示。
一旦事件触发,我就捕获该事件,然后在单击我自己的安装按钮后使用该事件开始 native 安装对话。示例代码如下:
let deferredPrompt;
window.addEventListener('beforeinstallprompt', (e) => {
// Prevent Chrome 67 and earlier from automatically showing the prompt
e.preventDefault();
// Stash the event so it can be triggered later.
deferredPrompt = e;
// Update UI notify the user they can add to home screen
btnAdd.style.display = 'block';
});
btnAdd.addEventListener('click', (e) => {
// hide our user interface that shows our A2HS button
btnAdd.style.display = 'none';
// Show the prompt
deferredPrompt.prompt();
// Wait for the user to respond to the prompt
deferredPrompt.userChoice
.then((choiceResult) => {
if (choiceResult.outcome === 'accepted') {
console.log('User accepted the A2HS prompt');
} else {
console.log('User dismissed the A2HS prompt');
}
deferredPrompt = null;
});
});
我遇到的问题是,如果用户已经将网络应用程序安装到他们的主屏幕,我不想显示我的安装按钮 (btnAdd
),而且我是无法弄清楚如何检查该情况。
我希望将上面的代码修改如下:
window.addEventListener('beforeinstallprompt', (e) => {
// Prevent Chrome 67 and earlier from automatically showing the prompt
e.preventDefault();
// Stash the event so it can be triggered later.
deferredPrompt = e;
// If the user has not already installed...
deferredPrompt.userChoice
.then(choiceResult => {
if (choiceResult === undefined) {
// Update UI notify the user they can add to home screen
btnAdd.style.display = 'block';
}
});
});
如果用户已经安装,则不会显示安装按钮。但这似乎不起作用。看起来,如果他们还没有做出选择,访问 userChoice
只会直接通过 native 对话提示用户。
我不太确定 beforeinstallevent
是如何工作的,所以这甚至可能不是一个好的策略。理想情况下,我希望这会像 navigator.serviceWorker.ready()
那样工作,它返回一个 Promise,而不是使用浏览器事件来尝试确定什么时候准备好了。
无论如何,关于如何在显示我自己的主屏幕安装按钮之前检查用户是否已安装到主屏幕有什么想法吗?
编辑:正如 Mathias 评论的那样,在显示按钮之前检查事件就足够了。我相信我遇到的问题是使用 localhost 的结果,它似乎在安装后不断触发 beforeinstallprompt
事件,这不是预期的行为。托管代码解决了这个问题。
最佳答案
也许,在拦截自动弹出窗口之前不显示按钮?
或者
在您的代码中,检查窗口是否独立
如果是,则无需显示按钮
if (window.matchMedia('(display-mode: standalone)').matches) {
// do things here
// set a variable to be used when calling something
// e.g. call Google Analytics to track standalone use
}
这里是我的示例测试器
https://a2hs.glitch.me
关于javascript - 检查用户是否已经将 PWA 安装到 Chrome 的主屏幕?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51735869/