forked from expo/expo-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexpo-service-worker.js
94 lines (80 loc) · 2.54 KB
/
expo-service-worker.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
/* eslint-env serviceworker */
/**
* Store notification icon string in service worker.
* Ref: https://stackoverflow.com/a/35729334/2603230
*/
self.addEventListener('message', event => {
let data;
if (typeof event.data === 'string') {
try {
data = JSON.parse(event.data);
} catch (e) {}
}
if (data && data.fromExpoWebClient) {
self.notificationIcon = data.fromExpoWebClient.notificationIcon;
}
});
/**
* Add support for push notification.
*/
self.addEventListener('push', event => {
let payload = {};
try {
payload = event.data.json();
} catch (e) {
// If `event.data.text()` is not a JSON object, we just treat it
// as a plain string and display it as the body.
payload = { title: '', body: event.data.text() };
}
const title = payload.title;
const data = payload.data || payload.custom || {};
const options = {
body: payload.body,
data,
};
options.icon = data._icon || payload.icon || self.notificationIcon || null;
options.image =
data._richContent && data._richContent.image ? options.data._richContent.image : payload.image;
options.tag = data._tag || payload.collapseKey;
if (options.tag) {
options.renotify = data._renotify;
}
event.waitUntil(self.registration.showNotification(title, options));
});
// https://developer.mozilla.org/en-US/docs/Web/API/Clients
self.addEventListener('notificationclick', event => {
event.notification.close();
event.waitUntil(
(async () => {
const allClients = await self.clients.matchAll({
includeUncontrolled: true,
});
let appClient;
const path = event.notification.data._webPath || '/';
// If we already have a window open, use it.
for (const client of allClients) {
const url = new URL(client.url);
if (url.pathname === path) {
client.focus();
appClient = client;
break;
}
}
// If there is no existing window, open a new one.
if (!appClient) {
appClient = await self.clients.openWindow(path);
}
// Message the client:
// `origin` will always be `'selected'` in this case.
// https://docs.expo.io/versions/latest/sdk/notifications/#notification
appClient.postMessage({
origin: 'selected',
data: event.notification.data,
remote: !event.notification._isLocal,
});
})()
);
});
// TODO: Consider cache: https://github.com/expo/expo-cli/pull/844#issuecomment-515619883
// Import the script generated by workbox.
self.importScripts('service-worker.js');