installation - 服务人员不安装仅添加到主屏幕
问题描述
我正在尝试将 pwa 安装到我的移动设备上。我只能添加到主屏幕。有谁知道为什么会这样?
解决方案
要使您的 PWA 可安装,您需要满足以下要求:
- 一个网络清单,填写了正确的字段。
- 要从安全 (HTTPS) 域提供服务的网站。
- 代表设备上的应用程序的图标。
- 使用 fetch 事件处理程序注册的服务工作者,以使应用程序脱机工作(目前仅适用于 Android 的 chrome 需要)。
您必须在 index.html 部分中包含清单文件,如下所示
<link rel="manifest" href="name.webmanifest">
您的清单应包含以下字段,其中大部分是不言自明的。
{
"background_color": "purple",
"description": "Shows random fox pictures. Hey, at least it isn't cats.",
"display": "fullscreen",
"icons": [
{
"src": "icon/fox-icon.png",
"sizes": "192x192",
"type": "image/png"
}
],
"name": "Awesome fox pictures",
"short_name": "Foxes",
"start_url": "/pwa-examples/a2hs/index.html"
}
现在,当浏览器找到满足所有要求的清单文件时,它将触发安装前提示,因此您必须显示 A2HS 对话框。
笔记:
- 不同的浏览器有不同的安装标准,或者触发 beforeinstallprompt 事件。
- 从 Android 版 Chrome 68(2018 年 7 月稳定版)开始,Chrome 将不再显示添加到主屏幕横幅。如果网站满足添加到主屏幕的条件,Chrome 将显示迷你信息栏。
对于 A2HS 对话框:
在您的文档中添加一个按钮,以允许用户进行安装
<button class="add-button">Add to home screen</button>
提供一些样式
.add-button {
position: absolute;
top: 1px;
left: 1px;
}
现在在注册服务工作者的 JS 文件中添加以下代码
let deferredPrompt;
//reference to your install button
const addBtn = document.querySelector('.add-button');
//We hide the button initially because the PWA will not be available for
//install until it follows the A2HS criteria.
addBtn.style.display = 'none';
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 to notify the user they can add to home screen
addBtn.style.display = 'block';
addBtn.addEventListener('click', (e) => {
// hide our user interface that shows our A2HS button
addBtn.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;
});
});
});
推荐阅读
- java - 检查意图数据是否为空?
- c# - 指定的参数超出了有效值的范围。参数名称:gridview日期过滤器上的索引
- java - org.hibernate.MappingException:无法确定类型:表中的类:table1,列:[org.hibernate.mapping.Column(end_table2)]
- machine-learning - 岭回归与套索回归
- nativescript - 带有 NativeScript 的文档扫描仪
- php - 需要帮助使用 PHP Preg_match 的正则表达式来验证表单上的数字字段
- python - 在使用 h5py 创建数据集时,是否建议在 gzip 或 lzf 旁边同时使用“shuffle”和“fletcher32”过滤器?
- traefik - 我如何在 docker swarm 中使用 traefik2.0,我不知道应该使用哪些标签
- javascript - 如何使用 preact 进行手动代码拆分?
- r - getRetweeters() 返回一个 id 而 getRetweetCount() 返回 2 -- 在 twitteR 包中