const CACHE_NAME = 'maiji-pwa-1'
const CACHELIST = [
'/',
]
// const LEIBIE = ['image', 'font', 'script'];
const LEIBIE = ['image', 'font'];
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open(CACHE_NAME)
.then(function(cache) {
return cache.addAll(CACHELIST);
})
);
});
self.addEventListener('fetch', function(event) {
var request = event.request;
if (request.method != "POST") {
event.respondWith(
caches.match(request)
.then(res => {
//1. 如果请求的资源已被缓存,则直接返回
// console.log(res);
if (res) {
return res;
}
//2. 没有,则发起请求并缓存结果
let requestClone = request.clone();
return fetch(requestClone)
.then(netRes => {
if (!netRes || netRes.status !== 200) {
return netRes;
}
let responseClone = netRes.clone();
if (in_array(requestClone.destination, LEIBIE)) {
caches.open(CACHE_NAME)
.then(cache => {
cache.put(requestClone, responseClone)
});
return netRes;
} else {
return netRes;
}
});
})
)
}
})
self.addEventListener('activate', function(event) {
event.waitUntil(
caches.keys().then(keyList => {
return Promise.all(keyList.map(key => {
if (CACHE_NAME.indexOf(key) === -1) {
return caches.delete(key);
}
}));
})
);
});
// 当服务器端向客户端 push 数据时,会触发次事件
// 在 Application 中的 Service Workers 面板中,可以直接模拟服务器向客户端发送数据
// 这里我们推送的数据如下:
// {"msg":"this is a test","url":"https://www.baidu.com/","icon":"./app.png"}
self.addEventListener('push', function(event) {
// 检查服务端是否发来了任何有效载荷数据
console.log('event.data:', event.data.text()); // event.data: {"msg":"this is a test","url":"https://www.baidu.com/","icon":"./app.png"}
const payload = event.data ? JSON.parse(event.data.text()) : 'no payload';
console.log(payload); // {msg: "this is a test", url: "https://www.baidu.com/", icon: "./app.png"}
const title = 'Progressive Times';
event.waitUntil(
// 使用提供的信息来显示 Web 推送通知
self.registration.showNotification(title, {
body: payload.msg,
data: payload.url,
icon: payload.icon,
silent: true, //震动声音
tag: 'renotify',
renotify: true
})
);
});
self.addEventListener('notificationclick', (event) => {
console.log(event);
// 关闭当前的弹窗
event.notification.close();
// 在新窗口打开页面
// event.waitUntil(
// // event.notification.data 取出推送通知中的数据
// clients.openWindow(event.notification.data)
// );
});
function in_array(search, array) {
for (var i in array) {
if (array[i] == search) {
return i;
}
}
return false;
}
调用代码
// 判断浏览器是否支持 service worker
if (window.location.protocol == 'https:' && 'serviceWorker' in navigator) {
// load 事件完成之后才注册 service worker
window.addEventListener('load', function() {
// 注册 sw.js
navigator.serviceWorker.register('./ServiceWorker.js').then(function(registration) {
// 注册成功
//console.log('pwa 注册成功', registration.scope);
let v = window.localStorage.getItem('_pwa');
if (v != 'true') {
window.location.reload();
}
}).catch(function(err) {
// 注册失败:(
console.log('pwa 注册失败 ', err);
});
});
}
网站需要开启https协议