-
Notifications
You must be signed in to change notification settings - Fork 0
/
sw9.js
63 lines (54 loc) · 2.09 KB
/
sw9.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
console.log("sw9.js initialized!!!");
var messages = [];
self.addEventListener('fetch', function(e) {
//console.log('fetch:' + e.request.url);
var urlobj = new URL(e.request.url);
console.log(urlobj.searchParams.get("user"));
console.log(urlobj.searchParams.get("id"));
if (urlobj.searchParams.get("action") === "timeout") {
var result = (messages.length > 0) ? messages : null;
clients.matchAll().then(clients => {
console.log("Number of controlled clients:" + clients.length);
console.log('After resolve client id:' + e.clientId);
for (var i=0; i<clients.length; ++i) {
console.log('client:' + clients[i]);
}
});
console.log('client id:' + e.clientId);
e.respondWith(new Promise(function(accept, reject) {
setTimeout(function() {
//if (messages.length === 0)
//return;
console.log("sw.js: sending back to worker.js msg:" + result + " length:" + messages.length);
accept(new Response(result));
messages = []; // Do not clear the messsages for now, it voids the result in worker.js!!!
}, 1000);
}));
} else {
e.respondWith(fetch(e.request));
}
});
self.onmessage = function(event) {
if (event.data === 'claim') {
// console.log('sw.js claiming clients');
clients.claim();
} else if (event.data === 'resolveId') {
let obj = {};
obj.resolveIdDone = 1;
obj.winId = event.source.id;
clients.get(event.source.id).then((client) => {
console.log('sw post winId back to app.js winId:' + event.source.id);
client.postMessage(obj);
});
}
console.log(`sw.js receive from syncxhr.html with sourceid "${event.source.id}" And with data: "${event.data}"`);
messages.push(event.data);
}
self.addEventListener('install', function(event) {
console.log("sw.js install event:" + event);
event.waitUntil(self.skipWaiting()); // Activate worker immediately
});
self.addEventListener('activate', function(event) {
console.log("sw.js activate event:" + event);
event.waitUntil(self.clients.claim()); // Become available to all pages
});