-
Notifications
You must be signed in to change notification settings - Fork 0
/
sw.js
704 lines (638 loc) · 26.8 KB
/
sw.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
// PWA应用的版本
const CACHE_VERSION = '1.0.0';
// 常缓存文件,可自由添加
const BASE_CACHE_FILES = [
'https:///api.vv1234.cn/llxhq/css/dashlite.css',
'https:///api.vv1234.cn/llxhq/css/style.css',
'https://api.vv1234.cn/llxhq/fonts/Nioicon.ttf',
'https://api.vv1234.cn/llxhq/js/common.js',
'https://api.vv1234.cn/llxhq/js/nioapp.min.js',
'https://api.vv1234.cn/llxhq/js/script.js',
'https://api.vv1234.cn/llxhq/js/common.js',
'https://cdn.staticfile.org/jquery/3.6.0/jquery.min.js',
'https://cdn.staticfile.org/jquery/3.6.0/jquery.min.js',
'https://cdn.staticfile.org/jquery/3.6.0/jquery.min.js',
'https://cdn.staticfile.org/bootstrap/4.6.1/js/bootstrap.bundle.min.js',
'https://cdn.staticfile.org/layer/3.5.1/layer.js',
'https://api.vv1234.cn/js/fuqiang.js',
'https://cdn.staticfile.org/vue/2.6.14/vue.min.js',
'https://cdn.staticfile.org/axios/0.26.0/axios.min.js',
'https://wx1.vv1234.cn/favicon.ico'
];
// 离线缓存首页
const OFFLINE_CACHE_FILES = [
'https://api.vv1234.cn/llxhq/',
];
// 未找到缓存文件时返回
const NOT_FOUND_CACHE_FILES = [
'https://api.vv1234.cn/llxhq/',
];
// 离线缓存首页和未找到缓存文件时返回
const OFFLINE_PAGE = 'https://api.vv1234.cn/llxhq/';
const NOT_FOUND_PAGE = 'https://api.vv1234.cn/llxhq/';
const CACHE_VERSIONS = {
content: 'content-v' + CACHE_VERSION,
notFound: '404-v' + CACHE_VERSION,
offline: 'offline-v' + CACHE_VERSION,
};
// Define MAX_TTL's in SECONDS for specific file extensions
const MAX_TTL = {
'/': 3600,
html: 3600,
json: 86400,
js: 86400,
css: 86400,
png: 86400,
jpg: 86400,
};
const CACHE_STRATEGY = {
default: 'cacheFirst',
css_js: 'cacheFirst',
images: 'cacheFirst',
fonts: 'cacheFirst',
}
const CACHE_BLACKLIST = [
];
const neverCacheUrls = [/\/wp-admin/,/\/wp-login/,/\/api/,/preview=true/,/\/cart/,/ajax/,/login/,];
const SUPPORTED_METHODS = [
'GET',
];
// Check if current url is in the neverCacheUrls list
function pwaForWpcheckNeverCacheList(url) {
if ( this.match(url) ) {
return false;
}
return true;
}
/**
* pwaForWpisBlackListed
* @param {string} url
* @returns {boolean}
*/
function pwaForWpisBlackListed(url) {
return (CACHE_BLACKLIST.length > 0) ? !CACHE_BLACKLIST.filter((rule) => {
if(typeof rule === 'function') {
return !rule(url);
} else {
return false;
}
}).length : false
}
/**
* pwaForWpgetFileExtension
* @param {string} url
* @returns {string}
*/
function pwaForWpgetFileExtension(url) {
if (typeof url === 'string') {
let split_two = url.split('?');
let split_url = split_two[0];
let extension = split_url.split('.').reverse()[0].split('?')[0];
return (extension.endsWith('/')) ? '/' : extension;
}else{
return null;
}
}
/**
* pwaForWpgetTTL
* @param {string} url
*/
function pwaForWpgetTTL(url) {
if (typeof url === 'string') {
let extension = pwaForWpgetFileExtension(url);
if (typeof MAX_TTL[extension] === 'number') {
return MAX_TTL[extension];
} else {
return MAX_TTL["/"];
}
} else {
return MAX_TTL["/"];
}
}
/**
* pwaForWpinstallServiceWorker
* @returns {Promise}
*/
function pwaForWpinstallServiceWorker() {
return Promise.all(
[
caches.open(CACHE_VERSIONS.content)
.then(
(cache) => {
if(BASE_CACHE_FILES.length >0){
for (var i = 0; i < BASE_CACHE_FILES.length; i++) {
pwaForWpprecacheUrl(BASE_CACHE_FILES[i])
}
}
//return cache.addAll(BASE_CACHE_FILES);
}
),
caches.open(CACHE_VERSIONS.offline)
.then(
(cache) => {
return cache.addAll(OFFLINE_CACHE_FILES);
}
),
caches.open(CACHE_VERSIONS.notFound)
.then(
(cache) => {
return cache.addAll(NOT_FOUND_CACHE_FILES);
}
)
]
)
.then(() => {
return self.skipWaiting();
});
}
/**
* pwaForWpcleanupLegacyCache
* @returns {Promise}
*/
function pwaForWpcleanupLegacyCache() {
let currentCaches = Object.keys(CACHE_VERSIONS)
.map(
(key) => {
return CACHE_VERSIONS[key];
}
);
return new Promise(
(resolve, reject) => {
caches.keys()
.then(
(keys) => {
return legacyKeys = keys.filter(
(key) => {
return !~currentCaches.indexOf(key);
}
);
}
)
.then(
(legacy) => {
if (legacy.length) {
Promise.all(
legacy.map(
(legacyKey) => {
return caches.delete(legacyKey)
}
)
)
.then(
() => {
resolve()
}
)
.catch(
(err) => {
reject(err);
}
);
} else {
resolve();
}
}
)
.catch(
() => {
reject();
}
);
}
);
}
function pwaForWpprecacheUrl(url) {
if(!pwaForWpisBlackListed(url)) {
caches.open(CACHE_VERSIONS.content)
.then((cache) => {
cache.match(url)
.then((response) => {
if(!response) {
return fetch(url)
} else {
// already in cache, nothing to do.
return null
}
})
.then((response) => {
if(response) {
fetch(url).then(dataWrappedByPromise => dataWrappedByPromise.text())
.then(data => {
if(data){
const regex = /<img[^>]+src="(https:\/\/[^">]+)"/g;
let m;
while ((m = regex.exec(data)) !== null) {
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
m.forEach((match, groupIndex) => {
if(groupIndex == 1){
if(new URL(match).origin == location.origin){
fetch(match).
then((imagedata) => {
//console.log(imagedata);
cache.put(match, imagedata.clone());
});
}
}
});
}
}
});
return cache.put(url, response.clone());
} else {
return null;
}
});
})
}
}
var fetchRengeData = function(event){
var pos = Number(/^bytes\=(\d+)\-$/g.exec(event.request.headers.get('range'))[1]);
console.log('Range request for', event.request.url, ', starting position:', pos);
event.respondWith(
caches.open(CACHE_VERSIONS.content)
.then(function(cache) {
return cache.match(event.request.url);
}).then(function(res) {
if (!res) {
return fetch(event.request)
.then(res => {
return res.arrayBuffer();
});
}
return res.arrayBuffer();
}).then(function(ab) {
return new Response(
ab.slice(pos),
{
status: 206,
statusText: 'Partial Content',
headers: [
// ['Content-Type', 'video/webm'],
['Content-Range', 'bytes ' + pos + '-' +
(ab.byteLength - 1) + '/' + ab.byteLength]]
});
}));
}
let cachingStrategy = {
notGetMethods: function(event){
// If non-GET request, try the network first, fall back to the offline page
if (event.request.method !== 'GET') {
event.respondWith(
fetch(event.request)
.catch(error => {
return caches.match(offlinePage);
})
);
return false;
}
},
fetchFromCache: function(event){
/* return new Promise(
(resolve) => {*/
return caches.open(CACHE_VERSIONS.content)
.then(
(cache) => {
return cache.match(event.request)
.then(
(response) => {
if (response) {
let headers = response.headers.entries();
let date = null;
for (let pair of headers) {
if (pair[0] === 'date') {
date = new Date(pair[1]);
}
}
if (date) {
let age = parseInt((new Date().getTime() - date.getTime())/1000);
let ttl = pwaForWpgetTTL(event.request.url);
if (age > ttl) {
return new Promise(
(resolve) => {
return fetch(event.request.clone())
.then(
(updatedResponse) => {
if (updatedResponse) {
cache.put(event.request, updatedResponse.clone());
resolve(updatedResponse);
} else {
resolve(response)
}
}
)
.catch(
() => {
resolve(response);
}
);
}
)
.catch(
(err) => {
return response;
}
);
} else {
return response;
}
} else {
return response;
}
} else {
return null;
}
}
)
.then(
(response) => {
if (response) {
return response;
} else {
return fetch(event.request.clone())
.then(
(response) => {
if(response.status < 300) {
if (~SUPPORTED_METHODS.indexOf(event.request.method) && !pwaForWpisBlackListed(event.request.url)) {
cache.put(event.request, response.clone());
}
return response;
} else {
return caches.open(CACHE_VERSIONS.notFound).then((cache) => {
return cache.match(NOT_FOUND_PAGE);
})
}
}
)
.then((response) => {
if(response) {
return response;
}
})
.catch(
() => {
return caches.open(CACHE_VERSIONS.offline)
.then(
(offlineCache) => {
return offlineCache.match(OFFLINE_PAGE)
}
)
}
);
}
}
)
.catch(
(error) => {
console.error(' Error in fetch handler:', error);
throw error;
}
);
}
)
/*})*/
},
fetchnetwork: function(event){
return caches.open(CACHE_VERSIONS.content)
.then(
(cache) => {
return fetch(event.request.clone()).then(function (response) {
if(response.status < 300) {
if (~SUPPORTED_METHODS.indexOf(event.request.method) && !pwaForWpisBlackListed(event.request.url)) {
cache.put(event.request, response.clone());
}
return response;
}else if(response.status==404){
return cachingStrategy.Notfoundpage();
} else if( cache.match(event.request) ){
return cache.match(event.request);
}else {
return cachingStrategy.Offlinepage();
}
}).catch(
(err) => {
return cache.match(event.request)
}
).catch(
(err) => {
return cachingStrategy.Offlinepage();
}
)
}
).catch(
(err) => {
return cachingStrategy.Offlinepage();
}
)
},
addCache: function(event,updatedResponse){
cache.put(event.request, updatedResponse.clone());
resolve(updatedResponse);
},
Offlinepage: function(){
return caches.open(CACHE_VERSIONS.offline).then((cache) => {
return cache.match(OFFLINE_PAGE);
})
},
Notfoundpage: function(){
return caches.open(CACHE_VERSIONS.notFound).then((cache) => {
return cache.match(NOT_FOUND_PAGE);
})
},
/*Strategies*/
networkOnlyStrategy: function(event){
return caches.open(CACHE_VERSIONS.content)
.then(
(cache) => {
return fetch(event.request.clone()).then(function (response) {
if(response.status < 300) {
if (~SUPPORTED_METHODS.indexOf(event.request.method) && !pwaForWpisBlackListed(event.request.url)) {
cache.put(event.request, response.clone());
}
return response;
}else if(response.status==404){
return cachingStrategy.Notfoundpage();
} else if(cache.match(event.request)){
return cache.match(event.request)
} else {
return cachingStrategy.Offlinepage();
}
}).catch(
(err) => {
return cachingStrategy.Offlinepage();
}
)
}
).catch(
(err) => {
return cachingStrategy.Offlinepage()
}
);
},
cacheFirstStrategy: function(events){
return cachingStrategy.fetchFromCache(events).catch(
(err) => {
return cachingStrategy.Offlinepage()
}
);
},
NeworkFirstStrategy: function(events){
return cachingStrategy.fetchnetwork(events).catch(
(err) => {
return cachingStrategy.fetchFromCache(events)
}
).catch(
(err) => {
return cachingStrategy.Offlinepage()
}
);
}
}
self.addEventListener(
'install', event => {
event.waitUntil(
Promise.all([
pwaForWpinstallServiceWorker(),
self.skipWaiting(),
])
);
}
);
// The activate handler takes care of cleaning up old caches.
self.addEventListener(
'activate', event => {
event.waitUntil(
Promise.all(
[
pwaForWpcleanupLegacyCache(),
self.clients.claim(),
self.skipWaiting(),
]
)
.catch(
(err) => {
self.skipWaiting();
}
)
);
}
);
self.addEventListener('online', event => {
if (navigator.onLine && navigator.standalone === true) {
isReachable(event.request.url).then(function(online) {
if (online) {
//handle online status
caches.delete(event.request.url);
console.log('online');
} else {
console.log('no connectivity');
}
});
} else {
//handle offline status
console.log('offline');
}
});
function isReachable(url) {
/**
* Note: fetch() still "succeeds" for 404s on subdirectories,
* which is ok when only testing for domain reachability.
*/
return fetch(url, { method: 'HEAD', mode: 'no-cors' })
.then(function(resp) {
return resp && (resp.ok || resp.type === 'opaque');
})
.catch(function(err) {
console.warn('[conn test failure]:', err);
});
}
self.addEventListener(
'fetch', event => {
// Return if the current request url is in the never cache list
if ( ! neverCacheUrls.every(pwaForWpcheckNeverCacheList, event.request.url) ) {
//console.log( 'PWA ServiceWorker: URL exists in excluded list of cache.' + event.request.url);
return;
}
if(! neverCacheUrls.every(pwaForWpcheckNeverCacheList, event.request.referrer) ){
//console.log( 'PWA ServiceWorker: Ref-URL exists in excluded list of cache.' + event.request.referrer);
return;
}
if(pwaForWpisBlackListed(event.request.url)){
return;
}
// Return if request url protocal isn't http or https
if ( ! event.request.url.match(/^(http|https):\/\//i) )
return;
if ( event.request.referrer.match(/^(wp-admin):\/\//i) )
return;
if ( new URL(event.request.url).origin !== location.origin )
return;
if (event.request.headers.get('range')) {
fetchRengeData(event);
} else {
if(event.request.method !== 'GET' ){
event.respondWith(
fetch(event.request)
.catch(error => {
return caches.open(CACHE_VERSIONS.offline).then(function(cache) {
return cache.match(OFFLINE_URL);
});
})
);
return false;
}
const destination = event.request.destination;
switch (destination) {
case 'style':
case 'script':
cachingStrategyType = CACHE_STRATEGY.css_js;
break;
case 'document':
cachingStrategyType = CACHE_STRATEGY.default
break;
case 'image':
cachingStrategyType = CACHE_STRATEGY.images;
break;
case 'font':
cachingStrategyType = CACHE_STRATEGY.fonts;
break;
// All `XMLHttpRequest` or `fetch()` calls where
// `Request.destination` is the empty string default value
default:
cachingStrategyType = CACHE_STRATEGY.default
}
var cache = null;
switch(cachingStrategyType){
case "networkFirst":
cache = cachingStrategy.NeworkFirstStrategy(event)
break;
case "networkOnly":
cache = cachingStrategy.networkOnlyStrategy(event)
break;
//break;
case "cacheFirst":
case "staleWhileRevalidate":
default:
cache = cachingStrategy.cacheFirstStrategy(event)
break;
}
event.respondWith(cache);
}
}
);
self.addEventListener('message', (event) => {
if(
typeof event.data === 'object' &&
typeof event.data.action === 'string'
) {
switch(event.data.action) {
case 'cache' :
pwaForWpprecacheUrl(event.data.url);
break;
default :
console.log('Unknown action: ' + event.data.action);
break;
}
}
});