ServiceWorker
Service Worker
它采用
生命周期

// 当浏览器解析完 SW 文件时触发 install 事件
self.addEventListener("install", function (e) {
// install 事件中一般会将 cacheList 中要换存的内容通过 addAll 方法,请求一遍放入 caches 中
e.waitUntil(
caches.open(cacheStorageKey).then(function (cache) {
return cache.addAll(cacheList);
})
);
});
然后在
// 激活时触发 activate 事件
self.addEventListener("activate", function (e) {
var cacheDeletePromises = caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames.map((name) => {
if (name !== cacheStorageKey) {
return caches.delete(name);
} else {
return Promise.resolve();
}
})
);
});
e.waitUntil(Promise.all([cacheDeletePromises]));
});
self.addEventListener('fetch', function(e) {
// 在此编写缓存策略
e.respondWith(
// 可以通过匹配缓存中的资源返回
caches.match(e.request)
// 也可以从远端拉取
fetch(e.request.url)
// 也可以自己造
new Response('自己造')
// 也可以通过吧 fetch 拿到的响应通过 caches.put 方法放进 caches
);
});
离线offline 页面
在用户断网情况下,通常会出现浏览器自带的网络崩溃页面,给人一种

推送通知

推送通知使用两个
Notification API
self.registration.showNotification("PWA-Book-Demo 测试 actions", {
body: "点赞按钮可点击",
actions: [
{
action: "like",
title: "点赞",
icon: "/assets/images/like-icon.png",
},
],
});
// 监听通知点击事件
self.addEventListener("notificationclick", function (e) {
// 关闭通知
e.notification.close();
if (e.action === "like") {
// 点击了“点赞”按钮
console.log("点击了点赞按钮");
} else {
// 点击了对话框的其他部分
console.log("点击了对话框");
}
});
Push API
// 监听 push 事件
self.addEventListener("push", function (e) {
if (!e.data) {
return;
}
// 解析获取推送消息
let payload = e.data.text();
// 根据推送消息生成桌面通知并展现出来
let promise = self.registration.showNotification(payload.title, {
body: payload.body,
icon: payload.icon,
data: {
url: payload.url,
},
});
e.waitUntil(promise);
});
// 监听通知点击事件
self.addEventListener("notificationclick", function (e) {
// 关闭窗口
e.notification.close();
// 打开网页
e.waitUntil(self.clients.openWindow(e.data.url));
});