Skip to content

Instantly share code, notes, and snippets.

@theking2
Last active September 29, 2024 13:35
Show Gist options
  • Select an option

  • Save theking2/26b9a2c311b51dd51f99608daade24f8 to your computer and use it in GitHub Desktop.

Select an option

Save theking2/26b9a2c311b51dd51f99608daade24f8 to your computer and use it in GitHub Desktop.
JS Notification
/**
* class NotificationAlert asks for notification
* permission and shows notifications or alerts
*/
class NotificationAlert {
#title
constructor(title) {
this.#title = title;
this.#askNotificationPermission();
}
/**
* ask permissions for Notification, if not granted use alerts
*/
#askNotificationPermission() {
function handlePermission(permission) {
if (!('permission' in Notification)) {
Notification.permission = permission;
}
if (permission === 'denied' || permission === 'default') {
console.log('Notification permission was denied.');
} else {
console.log('Notification permission granted.');
}
}
if (!("Notification" in window)) {
console.log("This browser does not support notifications.");
} else {
Notification.requestPermission().then((permission) => {
handlePermission(permission);
});
}
}
/**
* show notification
* @param {string} message notification text to be shown
*/
showNotificationOrAlert(message) {
if (Notification.permission === 'granted') {
new Notification(this.#title, {
body: message
});
} else {
alert(message);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment