firebase-messaging-sw.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. importScripts('https://www.gstatic.com/firebasejs/10.13.2/firebase-app-compat.js');
  2. importScripts('https://www.gstatic.com/firebasejs/10.13.2/firebase-messaging-compat.js');
  3. importScripts('swenv.js')
  4. if ('serviceWorker' in navigator) {
  5. navigator.serviceWorker.register('./firebase-messaging-sw.js').then(function (reg) {
  6. console.log('reg: ', reg.scope);
  7. }).catch(function (err) {
  8. console.log('err: ', err);
  9. })
  10. }
  11. class CustomPushEvent extends Event {
  12. constructor(data) {
  13. super('push')
  14. Object.assign(this, data)
  15. this.custom = true
  16. }
  17. }
  18. firebase.initializeApp({
  19. apiKey: process.env.NEXT_PUBLIC_FIREBASE_APIKEY,
  20. authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTHDOMAIN,
  21. projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECTID,
  22. storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGEBUCKET,
  23. messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGINGSENDERID,
  24. appId: process.env.NEXT_PUBLIC_FIREBASE_APPID,
  25. measurementId: process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENTID,
  26. });
  27. // Retrieve an instance of Firebase Messaging so that it can handle background
  28. // messages.
  29. self.addEventListener('push', (e) => {
  30. // Skip if event is our own custom event
  31. console.log(`🚀🚀🚀🚀🚀-> in firebase-messaging-sw.js on 41`, e);
  32. if (e.custom) return;
  33. // Kep old event data to override
  34. let oldData = e.data
  35. // Create a new event to dispatch, pull values from notification key and put it in data key,
  36. // and then remove notification key
  37. let newEvent = new CustomPushEvent({
  38. data: {
  39. json() {
  40. let newData = oldData.json()
  41. newData.data = {
  42. ...newData.data,
  43. ...newData.notification
  44. }
  45. delete newData.notification
  46. return newData
  47. },
  48. },
  49. waitUntil: e.waitUntil.bind(e),
  50. })
  51. // Stop event propagation
  52. e.stopImmediatePropagation()
  53. // Dispatch the new wrapped event
  54. dispatchEvent(newEvent)
  55. })
  56. const messaging = firebase.messaging();
  57. messaging.onBackgroundMessage( (payload) => {
  58. console.log(`🚀🚀🚀🚀🚀-> in firebase-messaging-sw.js on 24`,payload)
  59. // Customize notification here
  60. const notificationTitle = payload.data.title;
  61. const notificationOptions = {
  62. body: payload.data.body,
  63. icon: payload.data.image,
  64. data: payload.data,
  65. ...payload.data
  66. };
  67. return self.registration.showNotification(notificationTitle,
  68. notificationOptions);
  69. });
  70. self.onnotificationclick = function (event) {
  71. console.log(`🚀🚀🚀🚀🚀-> in firebase-messaging-sw.js on 91`,event);
  72. //example
  73. self.clients.openWindow('/')
  74. event.notification.close()
  75. }