公司需求要做一个点击将该网页添加到主屏幕的功能
如何实现
//sw.js
self.addEventListener('fetch', e => {
// console.log('拦截:', e.request.url);
});
self.addEventListener('install', (e) => {
e.waitUntil(self.skipWaiting()); // 跳过等待,直接激活
console.log('install...');
});
self.addEventListener('activate', (e) => {
e.waitUntil(self.clients.claim()); // 激活后立刻让serviceWorker拥有控制权
console.log('activate....');
});
<link rel="manifest" href="./manifest.json">
<button class="add-button">Add to home screen</button>
<script>
window.addEventListener('load', async () => {
// 判断浏览器是否兼容service worker
if ('serviceWorker' in navigator) {
let registration = await navigator.serviceWorker.register('/sw.js');
}
});
</script>
let deferredPrompt;
const addBtn = document.querySelector('.add-button');
addBtn.style.display = 'none';
window.addEventListener('beforeinstallprompt', (e) => {
// 防止 Chrome 67 及更早版本自动显示安装提示
e.preventDefault();
// 稍后再触发此事件
deferredPrompt = e;
// 更新 UI 以提醒用户可以将 App 安装到桌面
addBtn.style.display = 'block';
addBtn.addEventListener('click', (e) => {
// 隐藏显示 A2HS 按钮的界面
addBtn.style.display = 'none';
// 显示安装提示
deferredPrompt.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) => {
console.log('应用安装');
//这里可以做埋点
});
mainfest.json文件
自行配置即可
{
"background_color": "purple",
"display": "fullscreen",
"icons": [
{
"src": "company.png",
"sizes": "192x192",
"type": "image/png"
}
],
"name": "xx快捷版",
"short_name": "快",
"start_url": "."
}