Skip to content

Instantly share code, notes, and snippets.

@N0taN3rd
Created May 26, 2017 04:39
Show Gist options
  • Select an option

  • Save N0taN3rd/d7e902f2736952b20ec4066fe2a64e4b to your computer and use it in GitHub Desktop.

Select an option

Save N0taN3rd/d7e902f2736952b20ec4066fe2a64e4b to your computer and use it in GitHub Desktop.
/* eslint-disable */
'use strict';
function showNotification(title, body, icon, tag, url) {
var notificationOptions = {
body: body,
icon: icon,
data: { url: url },
tag: tag
}
return self.registration.showNotification(title, notificationOptions);
}
self.addEventListener('push', function(event) {
var payload = event.data.json();
event.waitUntil(
self.registration.getNotifications({ tag: payload.tag }).then(function(notifications) {
if (notifications && notifications.length > 0) {
notifications.forEach(function(notification) {
notification.close();
});
}
return showNotification(payload.title, payload.body, payload.icon, payload.tag, payload.url);
})
);
});
self.addEventListener('notificationclick', function(event) {
// Android doesn't close the notification when you click on it
// See: http://crbug.com/463146
event.notification.close();
var url = event.notification.data.url;
// This looks to see if the current window is already open and
// focuses if it is
event.waitUntil(
clients.matchAll({ type: "window" })
.then(function(clientList) {
var reusedClientWindow = clientList.some(function(client) {
if (client.url === url && 'focus' in client) {
client.focus();
return true;
}
if ('navigate' in client && 'focus' in client) {
client.focus();
client.navigate(url);
return true;
}
return false;
});
if (!reusedClientWindow && clients.openWindow) return clients.openWindow(url);
})
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment