Created
December 1, 2020 11:29
-
-
Save m3h0w/b1d7b3c57d1c23c0d8d91a98a0d11b8d to your computer and use it in GitHub Desktop.
Firebase messaging service worker for displaying notifications that lead to the application
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
importScripts('https://www.gstatic.com/firebasejs/7.18.0/firebase-app.js'); | |
importScripts('https://www.gstatic.com/firebasejs/7.18.0/firebase-messaging.js'); | |
const config = { | |
apiKey: process.env.REACT_APP_FIREBASE_KEY, | |
authDomain: process.env.REACT_APP_FIREBASE_DOMAIN, | |
databaseURL: process.env.REACT_APP_FIREBASE_DATABASE, | |
projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID, | |
storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET, | |
messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID, | |
appId: process.env.REACT_APP_FIREBASE_APP_ID, | |
}; | |
firebase.initializeApp(config); | |
const messaging = firebase.messaging(); | |
// console.log('In firebase messaging worker: initalized firebase.messagings'); | |
messaging.setBackgroundMessageHandler(function (payload) { | |
// console.log('[firebase-messaging-sw.js] Received background message ', payload); | |
const notificationTitle = 'Event!'; | |
const notificationOptions = { | |
body: payload.data.text, | |
icon: '/icon-192.png', | |
}; | |
return self.registration.showNotification(notificationTitle, notificationOptions); | |
}); | |
self.addEventListener('notificationclick', (e) => { | |
e.notification.close(); | |
const rootUrl = new URL('/', location).href; | |
// Focus tab if open | |
e.waitUntil( | |
clients | |
.matchAll({ | |
includeUncontrolled: true, | |
type: 'window', | |
}) | |
.then(function (clientList) { | |
for (var i = 0; i < clientList.length; ++i) { | |
var client = clientList[i]; | |
if (client.url === rootUrl && 'focus' in client) { | |
return client.focus(); | |
} | |
} | |
if (clients.openWindow) { | |
return clients.openWindow('/'); | |
} | |
}) | |
); | |
}); |
and how you make 'process' available in service worker ?????
Pretty sure he never actually tried running this in the first place
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks! I actually did get all of this figured out and working, and then I got puzzled by why it was crashing on IOS, and then I had another one of my many facepalms at apple :(