|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +self.addEventListener('push', function(event) { |
| 4 | + console.log('Received a push message', event); |
| 5 | + var title = 'Anacondapp'; |
| 6 | + var icon = '/images/icon-192x192.png'; |
| 7 | + var tag = 'anacondapp'+Date.now(); |
| 8 | + |
| 9 | + var notificationPromise = event.currentTarget.registration.pushManager.getSubscription().then(function(sub) { |
| 10 | + var id = sub.endpoint.split('/').pop(); |
| 11 | + return fetch('/communications/details?token='+id); |
| 12 | + }).then(function(response){ |
| 13 | + return response.text(); |
| 14 | + }).then(function(body) { |
| 15 | + return self.registration.showNotification(title, { |
| 16 | + body: body, |
| 17 | + icon: icon, |
| 18 | + tag: tag |
| 19 | + }); |
| 20 | + }); |
| 21 | + |
| 22 | + event.waitUntil(notificationPromise); |
| 23 | + |
| 24 | + // Close after 5 seconds if still there - more browser like than mobile phone |
| 25 | + notificationPromise.then(function() { |
| 26 | + return new Promise(function(resolve){ |
| 27 | + setTimeout(resolve, 5000) |
| 28 | + }); |
| 29 | + }).then(function() { |
| 30 | + return event.currentTarget.registration.getNotifications(); |
| 31 | + }).then(function(notifications) { |
| 32 | + for(var i=0;i<notifications.length;i++){ |
| 33 | + var notification = notifications[i]; |
| 34 | + if(notification.tag === tag){ |
| 35 | + notification.close(); |
| 36 | + break; |
| 37 | + } |
| 38 | + } |
| 39 | + }); |
| 40 | +}); |
| 41 | + |
| 42 | + |
| 43 | +self.addEventListener('notificationclick', function(event) { |
| 44 | + console.log('On notification click: ', event); |
| 45 | + // Android doesn’t close the notification when you click on it |
| 46 | + // See: http://crbug.com/463146 |
| 47 | + event.notification.close(); |
| 48 | + |
| 49 | + // This looks to see if the current is already open and |
| 50 | + // focuses if it is |
| 51 | + event.waitUntil(clients.matchAll({ |
| 52 | + type: "window" |
| 53 | + }).then(function(clientList) { |
| 54 | + for (var i = 0; i < clientList.length; i++) { |
| 55 | + var client = clientList[i]; |
| 56 | + if (client.url == '/' && 'focus' in client) |
| 57 | + return client.focus(); |
| 58 | + } |
| 59 | + if (clients.openWindow) |
| 60 | + return clients.openWindow('/'); |
| 61 | + })); |
| 62 | + |
| 63 | +}); |
0 commit comments