我为我的静态网站实现了PWA。Service Worker已成功注册,我的页面也按照我的预期在离线情况下工作,但真正的问题在于添加到主屏幕。
我使用了适当的图标包括manifest.json,但仍然看不到添加主屏幕的弹出窗口,而且尝试从检查中推送添加到主屏幕时只能看到弹出窗口。
这是我的网站URL:https://www.savesoftinc.com/
清单JSON:
{
"name": "Save Soft",
"short_name": "SaveSoft",
"start_url": ".",
"display": "standalone",
"background_color": "#fff",
"theme_color": "#0EC3F7",
"description": "IT Services & Solutions.",
"icons": [
{
"src": "\/android-icon-36x36.png",
"sizes": "36x36",
"type": "image\/png",
"density": "0.75"
},
{
"src": "\/android-icon-48x48.png",
"sizes": "48x48",
"type": "image\/png",
"density": "1.0"
},
{
"src": "\/android-icon-72x72.png",
"sizes": "72x72",
"type": "image\/png",
"density": "1.5"
},
{
"src": "\/android-icon-96x96.png",
"sizes": "96x96",
"type": "image\/png",
"density": "2.0"
},
{
"src": "\/android-icon-144x144.png",
"sizes": "144x144",
"type": "image\/png",
"density": "3.0"
},
{
"src": "\/android-icon-192x192.png",
"sizes": "192x192",
"type": "image\/png",
"density": "4.0"
},
{
"src": "\/ms-icon-512x512.png",
"sizes": "512x512",
"type": "image\/png",
"density": "5.0"
}
]
}
同时尝试以下代码以弹出横幅,正如谷歌建议的那样
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;
});
});
window.addEventListener('appinstalled', (evt) => {
app.logEvent('a2hs', 'installed');
});
但它显示错误:
Uncaught ReferenceError: btnAdd未定义
ref:https://developers.google.com/web/fundamentals/app-install-banners/
btnAdd
的元素。要么创建一个按钮并像那样调用变量,要么只是在其他事件中调用prompt()
(我不建议这样做)。 - Agash Thamo.e.preventDefault()
来阻止Chrome 67及更早版本的默认行为。例如,在你的第一个事件中尝试调用e.prompt()
。 - Agash Thamo.