pwa.js
2.14 KB
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
62
63
64
65
66
67
68
import $ from 'yoho-jquery';
import yoho from 'yoho-app';
const isHttps = location.protocol === 'https:';
function register() {
const t = window.STATIC_RESOURCE_HASH || '';
const staticServer = window.STATIC_RESOURCE_PATH || '';
navigator.serviceWorker.register(`/sw.js?t=${t}&staticServer=${staticServer}`, {
scope: '/'
}).then(() => {
if (window._hmt && window._hmt.push) {
window._hmt.push(['_trackEvent', 'SW registered', 'SUCCESS',
document.title, location.href]);
}
}).catch(err => {
if (window._hmt && window._hmt.push) {
window._hmt.push(['_trackEvent', 'SW registered', 'FAILED',
document.title, JSON.stringify(err)]);
}
});
}
function unregister() {
if (isHttps) {
navigator.serviceWorker.getRegistrations().then(registrations => {
for (let registration of registrations) {
registration.unregister().then(() => {
if (window._hmt && window._hmt.push) {
window._hmt.push(['_trackEvent', 'SW unregistered', 'SUCCESS',
document.title, location.href]);
}
}).catch(err => {
if (window._hmt && window._hmt.push) {
window._hmt.push(['_trackEvent', 'SW unregistered', 'FAILED',
document.title, JSON.stringify(err)]);
}
});
}
});
}
}
window.addEventListener('load', function() {
if ('serviceWorker' in navigator && isHttps) {
$.ajax({
url: '//m.yohobuy.com/api/switch',
dataType: 'jsonp',
cache: false,
success(res) {
const usePwa = isHttps && !yoho.isApp && res && res.usePwa;
if (usePwa) {
register();
} else {
unregister();
}
}
});
}
});
// 暂时不自动弹出添加到桌面按钮
window.addEventListener('beforeinstallprompt', function(e) {
e.preventDefault();
return false;
});