Skip to content

Instantly share code, notes, and snippets.

@sundayu
Created July 28, 2023 02:31
Show Gist options
  • Save sundayu/a0159c87ece7c7b6035404b087c6de8f to your computer and use it in GitHub Desktop.
Save sundayu/a0159c87ece7c7b6035404b087c6de8f to your computer and use it in GitHub Desktop.
Push notifications
// Check if the browser supports push notifications.
if ("serviceWorker" in navigator && "PushManager" in window) {
try {
// Register the service worker.
const swReg = await navigator.serviceWorker.register("/sw.js");
// Subscribe for push notifications.
const pushSubscription = await swReg.pushManager.subscribe({
userVisibleOnly: true
});
// Save the push subscription to the database.
savePushSubscription(pushSubscription);
} catch (error) {
// Handle errors.
console.error("Error subscribing for push notifications.", error);
}
} else {
// Push notifications are not supported by the browser.
console.error("Push notifications are not supported by the browser.");
}
@sundayu
Copy link
Author

sundayu commented Jul 28, 2023

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment