firebase-messaging-sw.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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.register('./firebase-messaging-sw.js').then(function (reg) {
  13. firebase.initializeApp({
  14. apiKey: process.env.NEXT_PUBLIC_FIREBASE_APIKEY,
  15. authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTHDOMAIN,
  16. projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECTID,
  17. storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGEBUCKET,
  18. messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGINGSENDERID,
  19. appId: process.env.NEXT_PUBLIC_FIREBASE_APPID,
  20. measurementId: process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENTID,
  21. });
  22. self.addEventListener('push', (e) => {
  23. console.log(`🚀🚀🚀🚀🚀-> in firebase-messaging-sw.js on 41`, e);
  24. if (e.custom) return;
  25. let oldData = e.data
  26. let newEvent = new CustomPushEvent({
  27. data: {
  28. json() {
  29. let newData = oldData.json()
  30. newData.data = {
  31. ...newData.data,
  32. ...newData.notification
  33. }
  34. delete newData.notification
  35. return newData
  36. },
  37. },
  38. waitUntil: e.waitUntil.bind(e),
  39. })
  40. e.stopImmediatePropagation()
  41. dispatchEvent(newEvent)
  42. })
  43. const messaging = firebase.messaging();
  44. messaging.onBackgroundMessage( (payload) => {
  45. console.log(`🚀🚀🚀🚀🚀-> in firebase-messaging-sw.js on 24`,payload)
  46. // Customize notification here
  47. const notificationTitle = payload.data.title;
  48. const notificationOptions = {
  49. body: payload.data.body,
  50. icon: payload.data.image,
  51. data: payload.data,
  52. ...payload.data
  53. };
  54. return self.registration.showNotification(notificationTitle,
  55. notificationOptions);
  56. });
  57. self.onnotificationclick = function (event) {
  58. //example
  59. self.clients.openWindow('/')
  60. event.notification.close()
  61. }
  62. console.log('reg: ', reg.scope);
  63. }).catch(function (err) {
  64. console.log('err: ', err);
  65. })
  66. }