pwa.js
2.49 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
69
70
import $ from 'yoho-jquery';
import yoho from 'js/yoho-app';
const canUse = location.protocol === 'https:' || location.hostname === 'localhost';
const isDev = process.env.NODE_ENV === 'development' || !process.env.NODE_ENV;
function register() {
if (canUse && navigator && navigator.serviceWorker && navigator.serviceWorker.register) {
navigator.serviceWorker.register(`/sw.js${isDev ? '?dev' : ''}`).then(() => {
if (window._hmt && window._hmt.push) {
window._hmt.push(['_trackEvent', 'SW registered', 'SUCCESS',
document.title, location.href]);
}
}).catch(err => {
console.error(err);
if (window._hmt && window._hmt.push) {
window._hmt.push(['_trackEvent', 'SW registered', 'FAILED',
document.title, JSON.stringify(err)]);
}
});
}
}
function unregister() {
if (canUse && navigator && navigator.serviceWorker && navigator.serviceWorker.getRegistrations) {
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() {
// Android WebView 中 UserAgent 不正确
if (!yoho.isApp && !(yoho.isAndroid && yoho.isWechat)) {
if ('serviceWorker' in navigator) {
$.ajax({
url: '//m.yohobuy.com/api/switch',
dataType: 'jsonp',
cache: false,
success(res) {
const usePwa = res && res.usePwa;
if (usePwa) {
register();
} else {
unregister();
}
}
});
}
}
});
// 暂时不自动弹出添加到桌面按钮
window.addEventListener('beforeinstallprompt', function(e) {
e.preventDefault();
return false;
});