push-notification-service
Version:
Push notification package for web applications using service worker
2 lines (1 loc) • 1.83 kB
JavaScript
!function(e,i){"object"==typeof exports&&"undefined"!=typeof module?i(exports):"function"==typeof define&&define.amd?define(["exports"],i):i((e="undefined"!=typeof globalThis?globalThis:e||self).PushNotificationClient={})}(this,(function(e){"use strict";e.PushNotificationClient=class{constructor(e){this.serverUrl=e.serverUrl,this.publicVapidKey=e.publicVapidKey,this.swPath=e.swPath||"/sw.js",this.userId=e.userId}urlBase64ToUint8Array(e){const i=(e+"=".repeat((4-e.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),t=window.atob(i),s=new Uint8Array(t.length);for(let e=0;e<t.length;++e)s[e]=t.charCodeAt(e);return s}async initialize(){"serviceWorker"in navigator&&"PushManager"in window||console.log("Push notifications are not supported");"granted"!==await Notification.requestPermission()&&console.log("Notification permission not granted");try{if(!this.publicVapidKey){const e=await fetch(`${this.serverUrl}/vapid-public-key`),i=await e.json();this.publicVapidKey=i.publicKey}const e=await navigator.serviceWorker.register(this.swPath);await navigator.serviceWorker.ready;let i=await e.pushManager.getSubscription();if(!i){const t=this.urlBase64ToUint8Array(this.publicVapidKey);i=await e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:t})}return await this.saveSubscription(i),i}catch(e){console.error(`Service Worker Registration failed: ${e.message}`)}}async saveSubscription(e){return(await fetch(`${this.serverUrl}/save-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:this.userId,key:e})})).json()}async sendNotification(e){try{return(await fetch(`${this.serverUrl}/send-notification`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).json()}catch(e){console.log(e)}}},Object.defineProperty(e,"__esModule",{value:!0})}));