UNPKG

@beenotung/tslib

Version:
56 lines (55 loc) 1.53 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.isSupportNotification = isSupportNotification; exports.requireNotification = requireNotification; exports.showNotification = showNotification; const defer_1 = require("./async/defer"); function isSupportNotification() { return 'Notification' in window; } async function requireNotification() { if (!isSupportNotification()) { return false; } const defer = (0, defer_1.createDefer)(); Notification.requestPermission(res => { if (res === 'granted') { defer.resolve(true); } else if (res === 'denied') { defer.resolve(false); } else { defer.reject(new Error('unexpected result:' + res)); } }); return defer.promise; } /** * alert can be used as fallback, otherwise will reject the promise * */ async function showNotification(msg, options, useAlert = true) { function fallback() { if (useAlert) { return alert(msg); } else { throw new Error('Notification is not supported'); } } if (!(await requireNotification()) || !('ServiceWorkerRegistration' in window)) { return fallback(); } try { return ServiceWorkerRegistration.prototype.showNotification(msg, options); } catch (e) { try { return new Notification(msg, options); } catch (e) { return fallback(); } } }