UNPKG

2.59 kBJavaScriptView Raw
1/* eslint-env serviceworker */
2
3/**
4 * Store notification icon string in service worker.
5 * Ref: https://stackoverflow.com/a/35729334/2603230
6 */
7self.addEventListener('message', event => {
8 let data;
9 if (typeof event.data === 'string') {
10 try {
11 data = JSON.parse(event.data);
12 } catch (e) {}
13 }
14
15 if (data && data.fromExpoWebClient) {
16 self.notificationIcon = data.fromExpoWebClient.notificationIcon;
17 }
18});
19
20/**
21 * Add support for push notification.
22 */
23self.addEventListener('push', event => {
24 let payload = {};
25 try {
26 payload = event.data.json();
27 } catch (e) {
28 // If `event.data.text()` is not a JSON object, we just treat it
29 // as a plain string and display it as the body.
30 payload = { title: '', body: event.data.text() };
31 }
32
33 const title = payload.title;
34 const data = payload.data || payload.custom || {};
35 const options = {
36 body: payload.body,
37 data,
38 };
39 options.icon = data._icon || payload.icon || self.notificationIcon || null;
40 options.image = data._richContent && data._richContent.image ? options.data._richContent.image : payload.image;
41 options.tag = data._tag || payload.collapseKey;
42 if (options.tag) {
43 options.renotify = data._renotify;
44 }
45
46 event.waitUntil(self.registration.showNotification(title, options));
47});
48
49// https://developer.mozilla.org/en-US/docs/Web/API/Clients
50self.addEventListener('notificationclick', event => {
51 event.notification.close();
52
53 event.waitUntil(
54 (async () => {
55 const allClients = await self.clients.matchAll({
56 includeUncontrolled: true,
57 });
58
59 let appClient;
60
61 const path = event.notification.data._webPath || '/';
62
63 // If we already have a window open, use it.
64 for (const client of allClients) {
65 const url = new URL(client.url);
66
67 if (url.pathname === path) {
68 client.focus();
69 appClient = client;
70 break;
71 }
72 }
73
74 // If there is no existing window, open a new one.
75 if (!appClient) {
76 appClient = await self.clients.openWindow(path);
77 }
78
79 // Message the client:
80 // `origin` will always be `'selected'` in this case.
81 // https://docs.expo.io/versions/latest/sdk/notifications/#notification
82 appClient.postMessage({
83 origin: 'selected',
84 data: event.notification.data,
85 remote: !event.notification._isLocal,
86 });
87 })()
88 );
89});
90
91// TODO: Consider cache: https://github.com/expo/expo-cli/pull/844#issuecomment-515619883
92// Import the script generated by workbox.
93self.importScripts('service-worker.js');