firebase-messaging-sw.js 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. class CustomPushEvent extends Event {
  2. constructor(data) {
  3. super("push");
  4. Object.assign(this, data);
  5. this.custom = true;
  6. }
  7. }
  8. if ("serviceWorker" in navigator) {
  9. importScripts("https://www.gstatic.com/firebasejs/10.13.2/firebase-app-compat.js");
  10. importScripts("https://www.gstatic.com/firebasejs/10.13.2/firebase-messaging-compat.js");
  11. importScripts("./swenv.js");
  12. navigator.serviceWorker
  13. .register("./firebase-messaging-sw.js")
  14. .then(function (reg) {
  15. firebase.initializeApp({
  16. apiKey: process.env.NEXT_PUBLIC_FIREBASE_APIKEY,
  17. authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTHDOMAIN,
  18. projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECTID,
  19. storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGEBUCKET,
  20. messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGINGSENDERID,
  21. appId: process.env.NEXT_PUBLIC_FIREBASE_APPID,
  22. measurementId: process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENTID,
  23. });
  24. self.addEventListener("push", (e) => {
  25. console.log(`🚀🚀🚀🚀🚀-> in firebase-messaging-sw.js on 41`, e);
  26. if (e.custom) return;
  27. let oldData = e.data;
  28. let newEvent = new CustomPushEvent({
  29. data: {
  30. json() {
  31. let newData = oldData.json();
  32. newData.data = {
  33. ...newData.data,
  34. ...newData.notification,
  35. };
  36. delete newData.notification;
  37. return newData;
  38. },
  39. },
  40. waitUntil: e.waitUntil.bind(e),
  41. });
  42. e.stopImmediatePropagation();
  43. dispatchEvent(newEvent);
  44. });
  45. const messaging = firebase.messaging();
  46. messaging.onBackgroundMessage((payload) => {
  47. console.log(`🚀🚀🚀🚀🚀-> in firebase-messaging-sw.js on 24`, payload);
  48. // Customize notification here
  49. const notificationTitle = payload.data.title;
  50. const notificationOptions = {
  51. body: payload.data.body,
  52. icon: payload.data.image,
  53. data: payload.data,
  54. ...payload.data,
  55. };
  56. return self.registration.showNotification(notificationTitle, notificationOptions);
  57. });
  58. self.onnotificationclick = function (event) {
  59. //example
  60. self.clients.openWindow("/");
  61. event.notification.close();
  62. };
  63. console.log("reg: ", reg.scope);
  64. })
  65. .catch(function (err) {
  66. console.log("err: ", err);
  67. });
  68. }