Created
May 17, 2018 22:42
-
-
Save DanyelMorales/76d7fd29f5efa8dea5e65cbd80ad2730 to your computer and use it in GitHub Desktop.
Desktop notifications simple implementation
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
/** | |
* Interfaz para acceder a notificaciones desktop | |
* | |
* DesktopNotification.$show("Hey", { | |
* body: `you have ${totalDisplayed} tasks to do`, | |
* icon: '/yourlogo.png' | |
* }); | |
* @author Daniel Vera Morales | |
*/ | |
export class DesktopNotification { | |
private notify: Notification; | |
public static $show(title: string, attributes: NotificationOptions, callback?: (this: Notification, ev: Event) => any): Promise<Notification> { | |
return (new DesktopNotification(title, attributes)).show(callback); | |
} | |
constructor(readonly title: string, readonly attributes: NotificationOptions) { } | |
/** | |
* Verifica que exista esta caracteristica en el navegador | |
*/ | |
isAvailable(): boolean { | |
return ("Notification" in window); | |
} | |
/** | |
* Despliega una notificación utilizando el titulo y los atributos del constructor. | |
* | |
* Opcionalmente recibe un callback para ser ejecutado cuando se disparé el evento | |
* onShow. | |
*/ | |
show(callback?: (this: Notification, ev: Event) => any): Promise<Notification> { | |
return new Promise<Notification>((accept, reject) => { | |
if (!this.isAvailable()) { | |
reject(); | |
} | |
this.hasPermission().then(() => { | |
const notification = new Notification(this.title, this.attributes); | |
if (callback) { | |
notification.onshow = callback; | |
} | |
accept(notification); | |
}).catch(reject); | |
}); | |
} | |
private hasPermission(): Promise<never> { | |
return new Promise<never>((accept, reject) => { | |
Notification.requestPermission(function (result) { | |
if (result === 'denied') | |
reject(); | |
else { | |
accept(); | |
} | |
}); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment