Skip to content

Instantly share code, notes, and snippets.

@theking2
Last active June 5, 2024 11:14
Show Gist options
  • Save theking2/0503fea33f499c6cd0a7c9d1591feaeb to your computer and use it in GitHub Desktop.
Save theking2/0503fea33f499c6cd0a7c9d1591feaeb to your computer and use it in GitHub Desktop.
JavaScript class for notifications
/**
* class Notifications asks for notification
*/
class NotificationAlert {
constructor() {
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
* @param {string} title of notification text to be shown
*/
showNotificationOrAlert(message, title) {
if (Notification.permission === 'granted') {
new Notification(title, {
body: message
});
} else {
alert(message);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment