UNPKG

@benshi.ai/js-sdk

Version:

Benshi SDK

79 lines (61 loc) 2.4 kB
import { EventEmitter } from 'events'; import { NotificationAction, NotificationDispatcher } from "./typings"; class BsBrowserNotification extends EventEmitter implements NotificationDispatcher { private allowed = false public clickedNotifications = {} public constructor() { super() if (this.permissionNeedsUserInteraction()) { document.querySelector('body').addEventListener('click', () => { this.requestUserPermission() }, true) } else { this.requestUserPermission() } } permissionNeedsUserInteraction(): boolean { const isFirefox = () => { // extracted from https://github.com/arasatasaygin/is.js/blob/master/is.js // another approach would be: // var isFirefox = typeof InstallTrigger !== 'undefined'; return navigator.userAgent.toLowerCase().match(/(?:firefox|fxios)\/(\d+)/) !== null } return isFirefox() } requestUserPermission() { Notification.requestPermission((result) => { this.allowed = result === 'granted' }); } show(title: string, body: string, id: number) { const options = { body, requireInteraction: true } if (!this.allowed) { console.warn('--- NOT ALLOWED TO SHOW NOTIFICATIONS ---') this.emit(NotificationAction.Block, id) return } const notification = new Notification(title, options) // the behavior when clicking on the notification is like that: // - [click on the notification] dispatched onclick and onclose // - [click on the "x" to close it] dispatched onclose // // neither stopInmediatePropagation nor stopPropagation change this behaviour notification.onclick = (evt: Event) => { this.clickedNotifications[id] = true evt.stopPropagation() } notification.onclose = (evt: Event) => { if (this.clickedNotifications[id]) { // notification has been clicked this.emit(NotificationAction.Open, id) } else { // notification has been discarded this.emit(NotificationAction.Discard, id) } } } } export default BsBrowserNotification