Last active
September 29, 2024 13:35
-
-
Save theking2/26b9a2c311b51dd51f99608daade24f8 to your computer and use it in GitHub Desktop.
JS Notification
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
| /** | |
| * 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