Skip to content

Instantly share code, notes, and snippets.

@m3h0w
Created December 1, 2020 11:29
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save m3h0w/b1d7b3c57d1c23c0d8d91a98a0d11b8d to your computer and use it in GitHub Desktop.
Save m3h0w/b1d7b3c57d1c23c0d8d91a98a0d11b8d to your computer and use it in GitHub Desktop.
Firebase messaging service worker for displaying notifications that lead to the application
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('/');
}
})
);
});
@codefist
Copy link

codefist commented Dec 1, 2020

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 :(

@jafar-jabr
Copy link

and how you make 'process' available in service worker ?????

@Nunobpinto
Copy link

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