Skip to content

Instantly share code, notes, and snippets.

@gensart-x
Created October 11, 2024 02:45
Show Gist options
  • Save gensart-x/18b56e2144269f3e2861588882ba5f9c to your computer and use it in GitHub Desktop.
Save gensart-x/18b56e2144269f3e2861588882ba5f9c to your computer and use it in GitHub Desktop.
JS Service Worker for Push Notification
// Show notification if some data pushed to the service worker
self.addEventListener('push', event => {
// Get the data from the push message
const notification = event.data.json();
// Show the notification
event.waitUntil(self.registration.showNotification(notification.title, {
body: notification.body,
icon: 'icon.png',
data: {
notifURL: notification.url
}
}))
})
// Handles click on notification
self.addEventListener('notificationclick', event => {
event.waitUntil(clients.openWindow(event.notification.data.notifURL))
})
// Notification data sample
const notification = {
title: 'Notification Title',
body: 'Notification Body',
url: '/?am_i_awesome=true'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment