-
Notifications
You must be signed in to change notification settings - Fork 29
/
sw.reg.mgr.js
61 lines (58 loc) · 1.9 KB
/
sw.reg.mgr.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
(function () {
register({
ver: 2,
path: ".",
name: "sw.js",
onUpdate: () => {},
onSuccess: () => {},
});
function register(config) {
if ("serviceWorker" in navigator) {
var swUrl = config.path + "/" + config.name + "?v=" + config.ver;
navigator.serviceWorker
.register(swUrl)
.then((swReg) => {
config.log && console.log("Service Worker 注册成功。", swReg);
if (config && config.onRegster) {
config.onRegister(swReg);
}
swReg.onupdatefound = () => {
var installingWorker = swReg.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === "installed") {
if (navigator.serviceWorker.controller) {
config.log && console.log("Service Worker 已安装更新。");
if (config && config.onUpdate) {
config.onUpdate(swReg);
}
} else {
config.log && console.log("Service Worker 已安装。");
if (config && config.onSuccess) {
config.onSuccess(swReg);
}
}
}
};
};
})
.catch((err) => {
if (config && config.onError) {
config.onError(err);
}
console.error("serviceWorker注册期间发生错误:", error);
});
}
}
function unregister() {
if ("serviceWorker" in navigator) {
navigator.serviceWorker.ready.then((swReg) => {
swReg.unregister((result) => {
result && console.log("Service Worker 注销成功");
});
});
}
}
})();