Created
July 28, 2023 02:31
-
-
Save sundayu/a0159c87ece7c7b6035404b087c6de8f to your computer and use it in GitHub Desktop.
Push notifications
This file contains hidden or 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
// 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."); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
via: https://web.dev/push-notifications-in-all-modern-browsers/