Skip to content

Instantly share code, notes, and snippets.

@Kareszrk
Forked from hawlik/serwice-worker.js
Created December 7, 2023 10:55
Show Gist options
  • Save Kareszrk/821fecfcadfe4ebeec1afa00416a8fe8 to your computer and use it in GitHub Desktop.
Save Kareszrk/821fecfcadfe4ebeec1afa00416a8fe8 to your computer and use it in GitHub Desktop.
service worker redirect to browser tab on push notification click event
//browser push notification "onClick" event heandler
self.addEventListener('notificationclick', function(event) {
console.log('[Service Worker] Notification click Received.');
event.notification.close();
/**
* if exists open browser tab with matching url just set focus to it,
* otherwise open new tab/window with sw root scope url
*/
event.waitUntil(clients.matchAll({
type: "window"
}).then(function(clientList) {
for (var i = 0; i < clientList.length; i++) {
var client = clientList[i];
if (client.url == self.registration.scope && 'focus' in client) {
return client.focus();
}
}
if (clients.openWindow) {
return clients.openWindow('/');
}
}));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment