forked from Nickersoft/push.js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserviceWorker.js
More file actions
89 lines (74 loc) · 2.66 KB
/
Copy pathserviceWorker.js
File metadata and controls
89 lines (74 loc) · 2.66 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
'use strict';
function isFunction(obj) {
return obj && {}.toString.call(obj) === '[object Function]';
}
function runFunctionString(funcStr) {
if (funcStr.trim().length > 0) {
var func = new Function(funcStr);
if (isFunction(func)) {
func();
}
}
}
self.addEventListener('message', function(event) {
self.client = event.source;
});
self.onnotificationclose = function(event) {
runFunctionString(event.notification.data.onClose);
/* Tell Push to execute close callback */
self.client.postMessage(
JSON.stringify({
id: event.notification.data.id,
action: 'close'
})
);
};
self.onnotificationclick = function(event) {
var link, origin, href;
if (
typeof event.notification.data.link !== 'undefined' &&
event.notification.data.link !== null
) {
origin = event.notification.data.origin;
link = event.notification.data.link;
href = origin.substring(0, origin.indexOf('/', 8)) + '/';
/* Removes prepending slash, as we don't need it */
if (link[0] === '/') {
link = link.length > 1 ? link.substring(1, link.length) : '';
}
event.notification.close();
/* This looks to see if the current is already open and focuses if it is */
event.waitUntil(
clients
.matchAll({
type: 'window'
})
.then(function(clientList) {
var client, full_url;
for (var i = 0; i < clientList.length; i++) {
client = clientList[i];
full_url = href + link;
/* Covers case where full_url might be http://example.com/john and the client URL is http://example.com/john/ */
if (
full_url[full_url.length - 1] !== '/' &&
client.url[client.url.length - 1] === '/'
) {
full_url += '/';
}
if (client.url === full_url && 'focus' in client) {
return client.focus();
}
}
if (clients.openWindow) {
return clients.openWindow('/' + link);
}
})
.catch(function(error) {
throw new Error(
'A ServiceWorker error occurred: ' + error.message
);
})
);
}
runFunctionString(event.notification.data.onClick);
};