Last active
March 18, 2021 18:08
-
-
Save deyvicode/343b96887fb40efbbad45b4adfd15e16 to your computer and use it in GitHub Desktop.
Service worker push notification #ServiceWorker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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