Skip to content

Instantly share code, notes, and snippets.

@DanyelMorales
Created May 17, 2018 22:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DanyelMorales/76d7fd29f5efa8dea5e65cbd80ad2730 to your computer and use it in GitHub Desktop.
Save DanyelMorales/76d7fd29f5efa8dea5e65cbd80ad2730 to your computer and use it in GitHub Desktop.
Desktop notifications simple implementation
/**
* 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