|
| 1 | +const options = <%= serialize(options) %> |
| 2 | +const version = options.firebaseVersion |
| 3 | +const messagingSenderId = options.messagingSenderId |
| 4 | + |
| 5 | +// Get ENV && set messagingSenderId |
| 6 | +if (this.location.hostname === 'localhost') { |
| 7 | + importScripts( |
| 8 | + 'https://www.gstatic.com/firebasejs/' + version + '/firebase-app.js' |
| 9 | + ) |
| 10 | + importScripts( |
| 11 | + 'https://www.gstatic.com/firebasejs/' + version + '/firebase-messaging.js' |
| 12 | + ) |
| 13 | + firebase.initializeApp({ |
| 14 | + messagingSenderId: messagingSenderId |
| 15 | + }) |
| 16 | +} else { |
| 17 | + // Only works on Firebase hosting! |
| 18 | + // other option, add PRD messagingSenderId = '337088779183' and do the same |
| 19 | + importScripts('/__/firebase/' + version + '/firebase-app.js') |
| 20 | + importScripts('/__/firebase/' + version + '/firebase-messaging.js') |
| 21 | + importScripts('/__/firebase/init.js') |
| 22 | +} |
| 23 | + |
| 24 | +// Retrieve an instance of Firebase Messaging so that it can handle background |
| 25 | +// messages. |
| 26 | +const messaging = firebase.messaging() |
| 27 | + |
| 28 | +messaging.setBackgroundMessageHandler(function(payload) { |
| 29 | + const data = payload.data |
| 30 | + const notificationTitle = data.title |
| 31 | + const notificationOptions = { |
| 32 | + body: data.message, |
| 33 | + icon: data.iconPath, |
| 34 | + vibrate: [200, 100, 200, 100, 200, 100, 200], |
| 35 | + actions: [ |
| 36 | + // See MARK 1 -> First item is always taken as click action |
| 37 | + { |
| 38 | + title: 'Visit', |
| 39 | + action: data.clickPath |
| 40 | + } |
| 41 | + ] |
| 42 | + } |
| 43 | + return self.registration.showNotification( |
| 44 | + notificationTitle, |
| 45 | + notificationOptions |
| 46 | + ) |
| 47 | +}) |
| 48 | + |
| 49 | +self.addEventListener('notificationclick', function(e) { |
| 50 | + const notification = e.notification |
| 51 | + // MARK 1 -> always takes first item |
| 52 | + const clickAction = notification.actions[0].action |
| 53 | + const action = e.action |
| 54 | + if (action === 'close') { |
| 55 | + notification.close() |
| 56 | + } else { |
| 57 | + clients.openWindow(clickAction) |
| 58 | + notification.close() |
| 59 | + } |
| 60 | +}) |
0 commit comments