-
Notifications
You must be signed in to change notification settings - Fork 7
/
pushbots-worker.js
7 lines (6 loc) · 2.5 KB
/
pushbots-worker.js
1
2
3
4
5
6
7
"use strict";
//PushBots application Id
var application_id = "597a50824a9efa36b68b4568",
//Track push notification opens on PushBots
tracking = true;
function detectBrowser(){var a,b=navigator.userAgent,c=b.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[],d=b.match(/(edge(?=\/))\/?\s*(\d+)/i)||[];return"Edge"===d[1]?{title:d[1],ver:d[2]}:/trident/i.test(c[1])?(a=/\brv[ :]+(\d+)/g.exec(b)||[],{title:"IE",ver:a[1]||""}):"Chrome"===c[1]&&(a=b.match(/\bOPR\/(\d+)/),null!=a)?{title:"Opera",ver:a[1]}:(c=c[2]?[c[1],c[2]]:[navigator.appName,navigator.appVersion,"-?"],null!=(a=b.match(/version\/(\d+)/i))&&c.splice(1,1,a[1]),{title:c[0],ver:c[1]})}self.addEventListener("push",function(a){var b=!1;a.data&&(b=a.data.json()),a.waitUntil(self.registration.pushManager.getSubscription().then(function(a){if(b){console.log(b);b = JSON.parse(b);var c=b.m.title,d=b.m.body,e={};void 0!=b.p&&(e=b.p),self.registration.showNotification(c,{icon:!!e.icon&&e.icon,body:d,requireInteraction:!!e.requireInteraction&&e.requireInteraction,data:e,renotify:!!e.renotify&&e.renotify,tag:!!e.tag&&e.tag})}else console.log("Browser doesn't support payload.")}))}),self.addEventListener("notificationclick",function(a){console.log("Notification click: tag ",a.notification.tag),a.notification.close();var b=a.notification.data.url,c=detectBrowser(),d="chrome"===c.title.toLowerCase()?2:3,e=a.notification.data.pb_n_id;e&&tracking&&dataStore.fetchItem("pushbots_ids","userId",function(b){void 0!=b.target.result&&fetch("https://api.pushbots.com/2/pushOpened",{method:"post",headers:{"Content-Type":"application/json","x-pushbots-appid":application_id},body:JSON.stringify({device_id:b.target.result.value,push_id:a.notification.data.pb_n_id,platform:d,date:new Date})})}),a.waitUntil(clients.matchAll({type:"window"}).then(function(a){for(var c=0;c<a.length;c++){var d=a[c];if(d.url===b&&"focus"in d)return d.focus()}if(clients.openWindow&&b)return clients.openWindow(b)}))});var dataStore={databaseName:"pushbots_db",databaseVersion:1,datastore:null,openDB:function(a){var c=this;if(c.datastore)return void a();var d=indexedDB.open(this.databaseName,this.databaseVersion);d.onerror=function(a){log("Database error: "+a.target.errorCode)},d.onsuccess=function(b){c.datastore=b.target.result,a()},d.onupgradeneeded=function(a){var b=a.target.result;b.createObjectStore("pushbots_ids",{keyPath:"type"})}},fetchItem:function(a,b,c){var d=this;this.openDB(function(){var e=d.datastore.transaction([a],"readonly"),f=e.objectStore(a);f.get(b).onsuccess=c})}};