Skip to content

Instantly share code, notes, and snippets.

@agronom81
Created February 22, 2021 19:01
Show Gist options
  • Save agronom81/901083ad157469db94348c254c0b5d15 to your computer and use it in GitHub Desktop.
Save agronom81/901083ad157469db94348c254c0b5d15 to your computer and use it in GitHub Desktop.
importScripts("https://www.gstatic.com/firebasejs/8.2.6/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/8.2.6/firebase-messaging.js");
try {
firebase.initializeApp({
apiKey: "AIzaSyAZW895vVsq-sGPPRm52fQI3V3j6yvylRc",
authDomain: "push-project-e1ffa.firebaseapp.com",
projectId: "push-project-e1ffa",
storageBucket: "push-project-e1ffa.appspot.com",
messagingSenderId: "237926722474",
appId: "1:237926722474:web:46601acb7c7a30e8bc59d3",
measurementId: "G-XQ36BHPE6Y"
});
var messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function (payload) {
console.log("Handling background message", payload);
// Copy data object to get parameters in the click handler
payload.data.data = JSON.parse(JSON.stringify(payload.data));
return self.registration.showNotification(
payload.data.title,
payload.data
);
});
self.addEventListener("notificationclick", function (event) {
const target = event.notification.data.click_action || "/";
event.notification.close();
// This looks to see if the current is already open and focuses if it is
event.waitUntil(
clients
.matchAll({
type: "window",
includeUncontrolled: true,
})
.then(function (clientList) {
// clientList always is empty?!
for (var i = 0; i < clientList.length; i++) {
var client = clientList[i];
if (client.url === target && "focus" in client) {
return client.focus();
}
}
return clients.openWindow(target);
})
);
});
messaging.onBackgroundMessage((payload) => {
console.log(
"[firebase-messaging-sw.js] Received background message ",
payload
);
// Customize notification here
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
};
self.registration.showNotification(
notificationTitle,
notificationOptions
);
});
} catch (e) {
console.log(e);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment