Skip to content

Instantly share code, notes, and snippets.

@deyvicode
Last active March 18, 2021 18:08
Show Gist options
  • Save deyvicode/343b96887fb40efbbad45b4adfd15e16 to your computer and use it in GitHub Desktop.
Save deyvicode/343b96887fb40efbbad45b4adfd15e16 to your computer and use it in GitHub Desktop.
Service worker push notification #ServiceWorker
// service worker
self.addEventListener('push', event => {
//console.log(JSON.parse(event.data.text()));
if (!(self.Notification && self.Notification.permission === 'granted')) {
return;
}
const sendNotification = (title, message, url) => {
return self.registration.showNotification(title, {
body: message,
icon: '/images/logo.png',
data: {
url: url
}
});
};
if (event.data) {
const response = JSON.parse(event.data.text());
event.waitUntil(
sendNotification(response.title, response.message, response.url)
);
}
});
self.addEventListener('notificationclick', event => {
let url = event.notification.data.url;
event.notification.close(); // Android needs explicit close.
event.waitUntil(
clients.matchAll({type: 'window'}).then( windowClients => {
// Check if there is already a window/tab open with the target URL
for (var i = 0; i < windowClients.length; i++) {
var client = windowClients[i];
// If so, just focus it.
if (client.url === url && 'focus' in client) {
return client.focus();
}
}
// If not, then open the target URL in a new window/tab.
if (clients.openWindow) {
return clients.openWindow(url);
}
})
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment