项目需求,需要在html5页面中实现,添加PC端桌面或者移动端桌面按钮的功能。经过调研,通过渐进式web应用pwa(Progressive Web Apps)实现添加到主屏幕中(Add to Home Screen,简称 A2HS)功,是现代智能手机浏览器中的一项功能,能够快捷的web页面添加到主屏幕中,通过快捷方式,单击快速访问。
1、使用环境要求:
目前浏览器支持A2HS主要如下:Mobile Chrome / Android Webview 从 31 版开始支持 A2HS,Opera for Android 从 32 版开始支持,Firefox for Android 从 58 版 开始支持。
2、 使用步骤如下:
- 1、需要创建manifest文件,该文件需要json格式编辑,该内容如下
{
"background_color": "#fff",//主屏幕显示的颜色
"theme_color":"#fff",//主题颜色
"orientation":"any",//web应用程序的顶级默认方向
"description": "play minigame",//web程序的一般描述
"display": "standalone",//web应用程序的首选显示模式
"icons": [
{
"src": "/weiyou.png",
"sizes": "192x192",
"type": "image/png"
}
],//显示桌面应用的图标
"name": "Minigame",//应用名称
"short_name": "Minigame",//应用名称简称
"start_url": "/?from=homescreen"//用户启动应用的url
}
文件名字叫做mini.webmanifest.json,在需要使用A2HS的文件里,通过link引用该文件。
<link rel="manifest" href="/mini.webmanifest.json">
- 2、在需要的页面,设置个按钮,初始设置不显示,通过浏览器符合
A2HS的标准,加载成功及注册完事件beforeinstallprompt后,才显示该按钮。
<button class="add_button_tohome" style="display: block;"><span d></span> Add To HomeScreen</button>
.add_button_tohome {
display: none;
position: fixed;
bottom: 20px;
left: 50%;
z-index: 100;
transform: translateX(-50%);
background: #378ef5;
color: #fff;
text-decoration: none;
padding: 10px 20px;
font-size: 15px;
line-height: 20px;
border-radius: 20px;
box-shadow: 0 4px 16px rgb(0 0 0 / 30%);
border: none;
}
- 3、需要实现
A2HS的前提,还要求注册 Service Worker
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register('./index.js')
.then(() => { console.log('Service Worker Registered'); });
}
其中index.js 文件内容如下,可以在离线状态调取对应数据:
self.addEventListener('install', function (e) {
e.waitUntil(
caches.open('Minigame').then(function (cache) {
return cache.addAll([
]);
})
);
});
self.addEventListener('fetch', function (e) {
//调用接口数据,保存本地缓存中
});
- 4、加载事件
beforeinstallprompt
let deferredPrompt;
const addBtn = document.querySelector('.add-button');
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', () => {
// 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;
});
});
});
- 5、最终实现效果如下图所示:
- 6、主要参考资料MDN