global.js
2.31 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
/**
* 全局引用js
* @author: feng.chen<feng.chen@yoho.cn>
* @date: 2017/03/15
*/
const $ = require('yoho-jquery');
const cookie = require('yoho-cookie');
const qs = require('yoho-qs');
const tip = require('plugin/tip');
const yoho = require('./yoho-app');
// 如果不是 App,就把这个 cookie 清理掉,解决之前缓存错误的问题 20171020
const isApp = qs.app_version || /YohoBuy/i.test(navigator.userAgent || '');
if (!isApp) {
cookie.remove('app_uid', 'app_version', 'app_client_type');
}
// App 的信息需要存下来
if (yoho.isApp && qs.uid && qs.app_version && qs.client_type) {
const options = {
path: '/'
};
// 如果 App 没有写 UID,或者写的不对,H5 写一下
if (!cookie.get('app_uid') || cookie.get('app_uid') === '0') {
qs.uid && cookie.set('app_uid', qs.uid, options);
qs.app_version && cookie.set('app_version', qs.app_version, options);
qs.client_type && cookie.set('app_client_type', qs.client_type, options);
qs.session_key && cookie.set('app_session_key', qs.session_key, options);
}
}
// 注册ajaxError处理服务端401状态
$(document).ajaxError((event, xhr) => {
if (xhr.status === 401) {
if (xhr.responseJSON && xhr.responseJSON.lowVersion) {
tip.show(xhr.responseJSON.message);
} else {
cookie.remove('_UID');
cookie.remove('_TOKEN');
if (yoho.isApp) {
yoho.goLogin(window.location.href);
} else {
window.location.href = `/signin.html?refer=${encodeURIComponent(window.location.href)}`;
}
}
}
});
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('/sw.js', {scope: '/'}).then(registration => {
console.log('SW registered: ', registration);
this.addEventListener('install', function(event) {
event.waitUntil(
caches.open('my-test-cache-v1').then(function(cache) {
return cache.addAll([
'/'
]);
})
);
});
}).catch(registrationError => {
console.log('SW registration failed: ', registrationError);
});
});
}