Last active
June 5, 2024 11:14
-
-
Save theking2/0503fea33f499c6cd0a7c9d1591feaeb to your computer and use it in GitHub Desktop.
JavaScript class for notifications
This file contains 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
/** | |
* 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