-
Notifications
You must be signed in to change notification settings - Fork 18
/
sw-register.js
45 lines (39 loc) · 1.27 KB
/
sw-register.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
const applicationServerPublicKey = 'BCx1qqSFCJBRGZzPaFa8AbvjxtuJj9zJie_pXom2HI-gisHUUnlAFzrkb-W1_IisYnTcUXHmc5Ie3F58M1uYhZU';
function urlB64ToUint8Array(base64String) {
const padding = '='.repeat((4 - base64String.length % 4) % 4);
const base64 = (base64String + padding)
.replace(/\-/g, '+')
.replace(/_/g, '/');
const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
function subscribeUser(swReg) {
const applicationServerKey = urlB64ToUint8Array(applicationServerPublicKey);
swReg.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: applicationServerKey
})
.then(function(subscription) {
console.log(JSON.stringify(subscription));
})
.catch(function(err) {
console.log('订阅失败: ', err);
});
}
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js').then(function (swReg) {
swReg.pushManager.getSubscription()
.then(function(subscription) {
if (subscription) {
console.log(JSON.stringify(subscription));
} else {
console.log('没有订阅');
subscribeUser(swReg);
}
});
});
}