pushilka 1.0.14 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/app.js CHANGED
@@ -1 +1 @@
1
- function Pushilka(e){var n,t,o=u(),i={endpoint:"https://swarmpush.com/push_subscription.php",eventEndpoint:"https://swarmpush.com/event",serviceWorker:"/serviceWorker.js",serviceWorkerOptions:{scope:"/"},applicationServerKey:"BCmIwkLHxJNPccoVf2UXDjd7kDuiyJpKsSOqSHCtGBMfBkjfHLCq4-d8eNtabNlCNKFF8CZIzeDwOo3OvNCQAns",source:"",var1:"",var2:"",var3:"",var4:"",var5:"",var6:"",var7:"",var8:"",var9:"",var10:"",useDialog:!1,visitorCookie:"pushilka_vid",dialog:{ttl:30,message:"We'd like to send you notifications for the latest news and updates.",allowText:"Allow",cancelText:"No thanks",icon:"https://swarmpush.com/s/pushilka/bell.webp",style:"https://swarmpush.com/s/pushilka/app.css",template:'<div id="pushilka-dialog" class="pushilka-dialog"><div class="pushilka-icon"><img width="80" src="{ICON_URL}" alt=""></div><div class="pushilka-message">{MESSAGE}</div><div class="pushilka-buttons"><a href="" id="pushilka-agree-button" class="pushilka-agree-button">{ALLOW_TEXT}</a><a href="" id="pushilka-cancel-button" class="pushilka-cancel-button">{CANCEL_TEXT}</a></div></div>'},done:function(){},success:function(){},decline:function(){}};for(t in e)if(e.hasOwnProperty(t)&&"dialog"===t)for(var r in e[t])e[t].hasOwnProperty(r)&&i[t].hasOwnProperty(r)&&(i[t][r]=e[t][r]);else e.hasOwnProperty(t)&&i.hasOwnProperty(t)&&(i[t]=e[t]);function a(e){fetch(i.eventEndpoint,{method:"POST",body:JSON.stringify({event:e,source:i.source,visitorId:l(),sessionId:o,var1:i.var1,var2:i.var2,var3:i.var3,var4:i.var4,var5:i.var5,var6:i.var6,var7:i.var7,var8:i.var8,var9:i.var9,var10:i.var10})}).catch()}function s(e,n,t){var o=new Date;o.setTime(o.getTime()+60*t*1e3),t="; expires="+o.toUTCString(),document.cookie=e+"="+(n||"")+t+"; path=/"}function c(e){var n,t=document.cookie.split(";"),o=e+"=";for(n in t){var r=t[n].trimLeft();if(0===r.indexOf(o))return r.substring(o.length)}return null}function d(){navigator.serviceWorker.ready.then(function(e){return a("sys_push_invoked"),e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:function(e){for(var e=(e+"=".repeat((4-e.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),n=window.atob(e),t=new Uint8Array(n.length),o=0;o<n.length;++o)t[o]=n.charCodeAt(o);return t}(i.applicationServerKey)})}).then(function(e){return v(e,"POST")}).catch(function(){a("sys_push_blocked"),i.decline(),i.done()})}function u(){for(var e=[],n=0;n<2;n++)e.push(Math.floor(4294967295*Math.random()).toString(36));return e.join("-")}function l(){var e=window.localStorage;return n=n||e.getItem("visitorId")||c(i.visitorCookie)||u(),e.setItem("visitorId",n),s(i.visitorCookie,n,365),n}function p(e){return e+"?vid="+encodeURIComponent(l())+"&sid="+encodeURIComponent(o)+"&s="+encodeURIComponent(i.source.toString())+"&var1="+encodeURIComponent(i.var1.toString())+"&var2="+encodeURIComponent(i.var2.toString())+"&var3="+encodeURIComponent(i.var3.toString())+"&var4="+encodeURIComponent(i.var4.toString())+"&var5="+encodeURIComponent(i.var5.toString())+"&var6="+encodeURIComponent(i.var6.toString())+"&var7="+encodeURIComponent(i.var7.toString())+"&var8="+encodeURIComponent(i.var8.toString())+"&var9="+encodeURIComponent(i.var9.toString())+"&var10="+encodeURIComponent(i.var10.toString())+"&timezone="+encodeURIComponent(function(){let e="";try{e=Intl.DateTimeFormat().resolvedOptions().timeZone}catch(e){console.error(e)}return e}())}function v(e,n){var t=e.getKey("p256dh"),o=e.getKey("auth"),r=(PushManager.supportedContentEncodings||["aesgcm"])[0];return fetch(p(i.endpoint),{method:n,body:JSON.stringify({endpoint:e.endpoint,publicKey:t?btoa(String.fromCharCode.apply(null,new Uint8Array(t))):null,authToken:o?btoa(String.fromCharCode.apply(null,new Uint8Array(o))):null,contentEncoding:r})}).then(function(){return i.success(),i.done(),e}).catch(function(){i.success(),i.done()})}this.ready=function(e){"interactive"===document.readyState||"complete"===document.readyState?e():document.addEventListener("DOMContentLoaded",e)},this.run=function(){this.ready(function(){"showNotification"in ServiceWorkerRegistration.prototype==!1?(console.debug("Push messaging is not supported."),a("push_not_supported"),i.decline(),i.done()):"denied"===Notification.permission?(console.debug("User has blocked notifications."),a("sys_push_blocked"),i.decline(),i.done()):navigator.serviceWorker.register(i.serviceWorker,i.serviceWorkerOptions).then(function(){navigator.serviceWorker.ready.then(function(e){return e.pushManager.getSubscription()}).then(function(e){return e?v(e,"PUT"):i.useDialog?void(null!==c("pushilka-dialog")?a("push_blocked"):(a("push_invoked"),e=i.dialog,(n=document.createElement("link")).rel="stylesheet",n.href=e.style,document.body.appendChild(n),(n=document.createElement("div")).innerHTML=e.template.replace("{ICON_URL}",e.icon).replace("{MESSAGE}",e.message).replace("{ALLOW_TEXT}",e.allowText).replace("{CANCEL_TEXT}",e.cancelText),document.body.appendChild(n),(t={agreeButton:document.getElementById("pushilka-agree-button"),cancelButton:document.getElementById("pushilka-cancel-button"),dialog:document.getElementById("pushilka-dialog")}).agreeButton.addEventListener("click",function(e){e.preventDefault(),t.dialog.remove(),d()}),t.cancelButton.addEventListener("click",function(e){e.preventDefault(),a("push_blocked"),s("pushilka-dialog","1",i.dialog.ttl),t.dialog.remove()}))):d();var n,t})}).catch(function(){a("sys_push_subscribe_error"),i.decline(),i.done()})})}}
1
+ export default class Pushilka{sessionId=null;visitorId=null;params=null;constructor(e){for(var t in this.sessionId=this.genRandomString(),this.params={endpoint:"https://swarmpush.com/push_subscription.php",eventEndpoint:"https://swarmpush.com/event",serviceWorker:"/serviceWorker.js",serviceWorkerOptions:{scope:"/"},applicationServerKey:"BCmIwkLHxJNPccoVf2UXDjd7kDuiyJpKsSOqSHCtGBMfBkjfHLCq4-d8eNtabNlCNKFF8CZIzeDwOo3OvNCQAns",source:"",var1:"",var2:"",var3:"",var4:"",var5:"",var6:"",var7:"",var8:"",var9:"",var10:"",useDialog:!1,visitorCookie:"pushilka_vid",dialog:{ttl:30,message:"We'd like to send you notifications for the latest news and updates.",allowText:"Allow",cancelText:"No thanks",icon:"https://swarmpush.com/s/pushilka/bell.webp",style:"https://swarmpush.com/s/pushilka/app.css",template:'<div id="pushilka-dialog" class="pushilka-dialog"><div class="pushilka-icon"><img width="80" src="{ICON_URL}" alt=""></div><div class="pushilka-message">{MESSAGE}</div><div class="pushilka-buttons"><a href="" id="pushilka-agree-button" class="pushilka-agree-button">{ALLOW_TEXT}</a><a href="" id="pushilka-cancel-button" class="pushilka-cancel-button">{CANCEL_TEXT}</a></div></div>'},done:function(){},success:function(){},decline:function(){}},e)if(e.hasOwnProperty(t)&&"dialog"===t)for(var r in e[t])e[t].hasOwnProperty(r)&&this.params[t].hasOwnProperty(r)&&(this.params[t][r]=e[t][r]);else e.hasOwnProperty(t)&&this.params.hasOwnProperty(t)&&(this.params[t]=e[t])}urlBase64ToUint8Array(e){var e=(e+"=".repeat((4-e.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),t=window.atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;++e)r[e]=t.charCodeAt(e);return r}sendEvent(e){fetch(this.params.eventEndpoint,{method:"POST",body:JSON.stringify({event:e,source:this.params.source,visitorId:this.getVisitorId(),sessionId:this.sessionId,var1:this.params.var1,var2:this.params.var2,var3:this.params.var3,var4:this.params.var4,var5:this.params.var5,var6:this.params.var6,var7:this.params.var7,var8:this.params.var8,var9:this.params.var9,var10:this.params.var10})}).catch()}setCookie(e,t,r){var s=new Date;s.setTime(s.getTime()+60*r*1e3),r="; expires="+s.toUTCString(),document.cookie=e+"="+(t||"")+r+"; path=/"}getCookie(e){var t,r=document.cookie.split(";"),s=e+"=";for(t in r){var a=r[t].trimStart();if(0===a.indexOf(s))return a.substring(s.length)}return null}showDialog(){let r=this;if(null!==this.getCookie("pushilka-dialog"))this.sendEvent("push_blocked");else{this.sendEvent("push_invoked");var e=this.params.dialog,s=document.createElement("link"),s=(s.rel="stylesheet",s.href=e.style,document.body.appendChild(s),document.createElement("div"));s.innerHTML=e.template.replace("{ICON_URL}",e.icon).replace("{MESSAGE}",e.message).replace("{ALLOW_TEXT}",e.allowText).replace("{CANCEL_TEXT}",e.cancelText),document.body.appendChild(s);let t={agreeButton:document.getElementById("pushilka-agree-button"),cancelButton:document.getElementById("pushilka-cancel-button"),dialog:document.getElementById("pushilka-dialog")};t.agreeButton.addEventListener("click",function(e){e.preventDefault(),t.dialog.remove(),r.subscribe()}),t.cancelButton.addEventListener("click",function(e){e.preventDefault(),r.sendEvent("push_blocked"),r.setCookie("pushilka-dialog","1",r.params.dialog.ttl),t.dialog.remove()})}}subscribe(){let t=this;navigator.serviceWorker.ready.then(function(e){return t.sendEvent("sys_push_invoked"),e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:t.urlBase64ToUint8Array(t.params.applicationServerKey)})}).then(function(e){return t.sendSubscriptionToServer(e,"POST")}).catch(function(){t.sendEvent("sys_push_blocked"),t.params.decline(),t.params.done()})}genRandomString(){var t=[];for(let e=0;e<2;e++)t.push(Math.floor(4294967295*Math.random()).toString(36));return t.join("-")}getVisitorId(){var e=window.localStorage;return this.visitorId=this.visitorId||e.getItem("visitorId")||this.getCookie(this.params.visitorCookie)||this.genRandomString(),e.setItem("visitorId",this.visitorId),this.setCookie(this.params.visitorCookie,this.visitorId,365),this.visitorId}getTimezone(){let e="";try{e=Intl.DateTimeFormat().resolvedOptions().timeZone}catch(e){console.error(e)}return e}getEndpoint(e){return e+"?vid="+encodeURIComponent(this.getVisitorId())+"&sid="+encodeURIComponent(this.sessionId)+"&s="+encodeURIComponent(this.params.source.toString())+"&var1="+encodeURIComponent(this.params.var1.toString())+"&var2="+encodeURIComponent(this.params.var2.toString())+"&var3="+encodeURIComponent(this.params.var3.toString())+"&var4="+encodeURIComponent(this.params.var4.toString())+"&var5="+encodeURIComponent(this.params.var5.toString())+"&var6="+encodeURIComponent(this.params.var6.toString())+"&var7="+encodeURIComponent(this.params.var7.toString())+"&var8="+encodeURIComponent(this.params.var8.toString())+"&var9="+encodeURIComponent(this.params.var9.toString())+"&var10="+encodeURIComponent(this.params.var10.toString())+"&timezone="+encodeURIComponent(this.getTimezone())}sendSubscriptionToServer(e,t){let r=this;var s=e.getKey("p256dh"),a=e.getKey("auth"),n=(PushManager.supportedContentEncodings||["aesgcm"])[0];return fetch(r.getEndpoint(r.params.endpoint),{method:t,body:JSON.stringify({endpoint:e.endpoint,publicKey:s?btoa(String.fromCharCode.apply(null,new Uint8Array(s))):null,authToken:a?btoa(String.fromCharCode.apply(null,new Uint8Array(a))):null,contentEncoding:n})}).then(function(){return r.params.success(),r.params.done(),e}).catch(function(){r.params.success(),r.params.done()})}ready(e){"interactive"===document.readyState||"complete"===document.readyState?e():document.addEventListener("DOMContentLoaded",e)}run(){let t=this;t.ready(function(){"showNotification"in ServiceWorkerRegistration.prototype?"denied"===Notification.permission?(console.debug("User has blocked notifications."),t.sendEvent("sys_push_blocked"),t.params.decline(),t.params.done()):navigator.serviceWorker.register(t.params.serviceWorker,t.params.serviceWorkerOptions).then(function(){navigator.serviceWorker.ready.then(function(e){return e.pushManager.getSubscription()}).then(function(e){return e?t.sendSubscriptionToServer(e,"PUT"):t.params.useDialog?t.showDialog():t.subscribe()})}).catch(function(){t.sendEvent("sys_push_subscribe_error"),t.params.decline(),t.params.done()}):(console.debug("Push messaging is not supported."),t.sendEvent("push_not_supported"),t.params.decline(),t.params.done())})}}
package/dist/bell.webp CHANGED
Binary file
package/gulpfile.js CHANGED
@@ -1,22 +1,22 @@
1
- const {series, src, dest} = require('gulp');
2
- const uglify = require('gulp-uglify');
3
- const uglifycss = require('gulp-uglifycss');
1
+ let gulp = require('gulp');
2
+ let uglify = require('gulp-uglify');
3
+ let uglifycss = require('gulp-uglifycss');
4
4
 
5
5
  function scripts() {
6
- return src('src/*.js')
6
+ return gulp.src('src/*.js')
7
7
  .pipe(uglify())
8
- .pipe(dest('dist/'));
8
+ .pipe(gulp.dest('dist/'));
9
9
  }
10
10
 
11
11
  function css() {
12
- return src('src/*.css')
12
+ return gulp.src('src/*.css')
13
13
  .pipe(uglifycss())
14
- .pipe(dest('dist/'))
14
+ .pipe(gulp.dest('dist/'))
15
15
  }
16
16
 
17
17
  function images() {
18
- return src('src/*.{webp,jpg,png,gif}')
19
- .pipe(dest('dist/'));
18
+ return gulp.src('src/*.{webp,jpg,png,gif}')
19
+ .pipe(gulp.dest('dist/'));
20
20
  }
21
21
 
22
- exports.default = series(scripts, css, images)
22
+ exports.default = gulp.series(scripts, css, images)
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "pushilka",
3
- "version": "1.0.14",
3
+ "version": "2.0.1",
4
4
  "description": "Web push client",
5
5
  "main": "./dist/app.js",
6
6
  "devDependencies": {
7
- "gulp": "^4.0.2",
7
+ "gulp": "^5.0.0",
8
8
  "gulp-uglify": "^3.0.2",
9
9
  "gulp-uglifycss": "^1.1.0"
10
10
  },
@@ -21,8 +21,8 @@
21
21
  "url": "https://github.com/pushilka/pushilka/issues"
22
22
  },
23
23
  "engines": {
24
- "npm": ">=9.0.0 <10.0.0",
25
- "node": ">=18.0.0 <19.0.0"
24
+ "npm": ">=10.0.0 <11.0.0",
25
+ "node": ">=22.0.0 <23.0.0"
26
26
  },
27
27
  "homepage": "https://github.com/pushilka/pushilka#readme"
28
28
  }
package/src/app.js CHANGED
@@ -1,107 +1,111 @@
1
- function Pushilka(options) {
2
- var sessionId = genRandomString(),
3
- visitorId;
4
-
5
- var params = {
6
- endpoint: "https://swarmpush.com/push_subscription.php",
7
- eventEndpoint: "https://swarmpush.com/event",
8
- serviceWorker: "/serviceWorker.js",
9
- serviceWorkerOptions: {scope: "/"},
10
- applicationServerKey: "BCmIwkLHxJNPccoVf2UXDjd7kDuiyJpKsSOqSHCtGBMfBkjfHLCq4-d8eNtabNlCNKFF8CZIzeDwOo3OvNCQAns",
11
- source: "",
12
- var1: "",
13
- var2: "",
14
- var3: "",
15
- var4: "",
16
- var5: "",
17
- var6: "",
18
- var7: "",
19
- var8: "",
20
- var9: "",
21
- var10: "",
22
- useDialog: false,
23
- visitorCookie: 'pushilka_vid',
24
- dialog: {
25
- ttl: 30,
26
- message: "We'd like to send you notifications for the latest news and updates.",
27
- allowText: "Allow",
28
- cancelText: "No thanks",
29
- icon: 'https://swarmpush.com/s/pushilka/bell.webp',
30
- style: 'https://swarmpush.com/s/pushilka/app.css',
31
- template: '<div id="pushilka-dialog" class="pushilka-dialog"><div class="pushilka-icon">'
32
- + '<img width="80" src="{ICON_URL}" alt=""></div><div class="pushilka-message">{MESSAGE}</div>'
33
- + '<div class="pushilka-buttons"><a href="" id="pushilka-agree-button" class="pushilka-agree-button">{ALLOW_TEXT}</a>'
34
- + '<a href="" id="pushilka-cancel-button" class="pushilka-cancel-button">{CANCEL_TEXT}</a></div></div>'
35
- },
36
- done: function () {
37
- },
38
- success: function () {
39
- },
40
- decline: function () {
41
- }
42
- };
1
+ export default class Pushilka {
2
+ sessionId = null;
3
+ visitorId = null;
4
+ params = null;
5
+
6
+ constructor(options) {
7
+ this.sessionId = this.genRandomString();
8
+ this.params = {
9
+ endpoint: "https://swarmpush.com/push_subscription.php",
10
+ eventEndpoint: "https://swarmpush.com/event",
11
+ serviceWorker: "/serviceWorker.js",
12
+ serviceWorkerOptions: {scope: "/"},
13
+ applicationServerKey: "BCmIwkLHxJNPccoVf2UXDjd7kDuiyJpKsSOqSHCtGBMfBkjfHLCq4-d8eNtabNlCNKFF8CZIzeDwOo3OvNCQAns",
14
+ source: "",
15
+ var1: "",
16
+ var2: "",
17
+ var3: "",
18
+ var4: "",
19
+ var5: "",
20
+ var6: "",
21
+ var7: "",
22
+ var8: "",
23
+ var9: "",
24
+ var10: "",
25
+ useDialog: false,
26
+ visitorCookie: 'pushilka_vid',
27
+ dialog: {
28
+ ttl: 30,
29
+ message: "We'd like to send you notifications for the latest news and updates.",
30
+ allowText: "Allow",
31
+ cancelText: "No thanks",
32
+ icon: 'https://swarmpush.com/s/pushilka/bell.webp',
33
+ style: 'https://swarmpush.com/s/pushilka/app.css',
34
+ template: '<div id="pushilka-dialog" class="pushilka-dialog"><div class="pushilka-icon">'
35
+ + '<img width="80" src="{ICON_URL}" alt=""></div><div class="pushilka-message">{MESSAGE}</div>'
36
+ + '<div class="pushilka-buttons"><a href="" id="pushilka-agree-button" class="pushilka-agree-button">{ALLOW_TEXT}</a>'
37
+ + '<a href="" id="pushilka-cancel-button" class="pushilka-cancel-button">{CANCEL_TEXT}</a></div></div>'
38
+ },
39
+ done: function () {
40
+ },
41
+ success: function () {
42
+ },
43
+ decline: function () {
44
+ }
45
+ };
43
46
 
44
- for (var i in options) {
45
- if (options.hasOwnProperty(i) && i === 'dialog') {
46
- for (var j in options[i]) {
47
- if (options[i].hasOwnProperty(j) && params[i].hasOwnProperty(j)) {
48
- params[i][j] = options[i][j];
47
+ for (let i in options) {
48
+ if (options.hasOwnProperty(i) && i === 'dialog') {
49
+ for (let j in options[i]) {
50
+ if (options[i].hasOwnProperty(j) && this.params[i].hasOwnProperty(j)) {
51
+ this.params[i][j] = options[i][j];
52
+ }
49
53
  }
54
+ } else if (options.hasOwnProperty(i) && this.params.hasOwnProperty(i)) {
55
+ this.params[i] = options[i];
50
56
  }
51
- } else if (options.hasOwnProperty(i) && params.hasOwnProperty(i)) {
52
- params[i] = options[i];
53
57
  }
54
58
  }
55
59
 
56
- function urlBase64ToUint8Array(base64String) {
57
- var padding = '='.repeat((4 - base64String.length % 4) % 4);
58
- var base64 = (base64String + padding)
60
+ urlBase64ToUint8Array(base64String) {
61
+ let padding = '='.repeat((4 - base64String.length % 4) % 4);
62
+ let base64 = (base64String + padding)
59
63
  .replace(/-/g, '+')
60
64
  .replace(/_/g, '/');
61
65
 
62
- var rawData = window.atob(base64);
63
- var outputArray = new Uint8Array(rawData.length);
66
+ let rawData = window.atob(base64);
67
+ let outputArray = new Uint8Array(rawData.length);
64
68
 
65
- for (var i = 0; i < rawData.length; ++i) {
69
+ for (let i = 0; i < rawData.length; ++i) {
66
70
  outputArray[i] = rawData.charCodeAt(i);
67
71
  }
68
72
  return outputArray;
69
73
  }
70
74
 
71
- function sendEvent(event) {
72
- fetch(params.eventEndpoint, {
75
+ sendEvent(event) {
76
+ fetch(this.params.eventEndpoint, {
73
77
  method: 'POST',
74
78
  body: JSON.stringify({
75
79
  event: event,
76
- source: params.source,
77
- visitorId: getVisitorId(),
78
- sessionId: sessionId,
79
- var1: params.var1,
80
- var2: params.var2,
81
- var3: params.var3,
82
- var4: params.var4,
83
- var5: params.var5,
84
- var6: params.var6,
85
- var7: params.var7,
86
- var8: params.var8,
87
- var9: params.var9,
88
- var10: params.var10,
80
+ source: this.params.source,
81
+ visitorId: this.getVisitorId(),
82
+ sessionId: this.sessionId,
83
+ var1: this.params.var1,
84
+ var2: this.params.var2,
85
+ var3: this.params.var3,
86
+ var4: this.params.var4,
87
+ var5: this.params.var5,
88
+ var6: this.params.var6,
89
+ var7: this.params.var7,
90
+ var8: this.params.var8,
91
+ var9: this.params.var9,
92
+ var10: this.params.var10,
89
93
  })
90
94
  }).catch();
91
95
  }
92
96
 
93
- function setCookie(name, value, expires) {
94
- var date = new Date;
97
+ setCookie(name, value, expires) {
98
+ let date = new Date;
95
99
  date.setTime(date.getTime() + 60 * expires * 1000);
96
100
  expires = "; expires=" + date.toUTCString();
97
101
  document.cookie = name + "=" + (value || "") + expires + "; path=/";
98
102
  }
99
103
 
100
- function getCookie(name) {
101
- var parts = document.cookie.split(";"),
104
+ getCookie(name) {
105
+ let parts = document.cookie.split(";"),
102
106
  prefix = name + "=";
103
- for (var i in parts) {
104
- var part = parts[i].trimLeft();
107
+ for (let i in parts) {
108
+ let part = parts[i].trimStart();
105
109
  if (part.indexOf(prefix) === 0) {
106
110
  return part.substring(prefix.length);
107
111
  }
@@ -110,22 +114,24 @@ function Pushilka(options) {
110
114
  return null;
111
115
  }
112
116
 
113
- function showDialog() {
114
- if (getCookie("pushilka-dialog") !== null) {
115
- sendEvent("push_blocked");
117
+ showDialog() {
118
+ let self = this;
119
+
120
+ if (this.getCookie("pushilka-dialog") !== null) {
121
+ this.sendEvent("push_blocked");
116
122
  return;
117
123
  }
118
124
 
119
- sendEvent("push_invoked");
125
+ this.sendEvent("push_invoked");
120
126
 
121
- var dialog = params.dialog;
127
+ let dialog = this.params.dialog;
122
128
 
123
- var s = document.createElement('link');
129
+ let s = document.createElement('link');
124
130
  s.rel = "stylesheet";
125
131
  s.href = dialog.style;
126
132
  document.body.appendChild(s);
127
133
 
128
- var d = document.createElement('div');
134
+ let d = document.createElement('div');
129
135
  d.innerHTML = dialog.template
130
136
  .replace('{ICON_URL}', dialog.icon)
131
137
  .replace('{MESSAGE}', dialog.message)
@@ -133,7 +139,7 @@ function Pushilka(options) {
133
139
  .replace('{CANCEL_TEXT}', dialog.cancelText);
134
140
  document.body.appendChild(d);
135
141
 
136
- var els = {
142
+ let els = {
137
143
  agreeButton: document.getElementById("pushilka-agree-button"),
138
144
  cancelButton: document.getElementById("pushilka-cancel-button"),
139
145
  dialog: document.getElementById("pushilka-dialog")
@@ -143,55 +149,56 @@ function Pushilka(options) {
143
149
  e.preventDefault();
144
150
 
145
151
  els.dialog.remove();
146
- subscribe();
152
+ self.subscribe();
147
153
  });
148
154
  els.cancelButton.addEventListener("click", function (e) {
149
155
  e.preventDefault();
150
156
 
151
- sendEvent("push_blocked");
152
- setCookie("pushilka-dialog", "1", params.dialog.ttl);
157
+ self.sendEvent("push_blocked");
158
+ self.setCookie("pushilka-dialog", "1", self.params.dialog.ttl);
153
159
  els.dialog.remove();
154
160
  });
155
161
  }
156
162
 
157
- function subscribe() {
163
+ subscribe() {
164
+ let self = this;
158
165
  navigator.serviceWorker.ready
159
166
  .then(function (serviceWorkerRegistration) {
160
- sendEvent("sys_push_invoked");
167
+ self.sendEvent("sys_push_invoked");
161
168
  return serviceWorkerRegistration.pushManager
162
169
  .subscribe({
163
170
  userVisibleOnly: true,
164
- applicationServerKey: urlBase64ToUint8Array(params.applicationServerKey)
171
+ applicationServerKey: self.urlBase64ToUint8Array(self.params.applicationServerKey)
165
172
  });
166
173
  })
167
174
  .then(function (subscription) {
168
- return sendSubscriptionToServer(subscription, 'POST');
175
+ return self.sendSubscriptionToServer(subscription, 'POST');
169
176
  })
170
177
  .catch(function () {
171
- sendEvent("sys_push_blocked");
172
- params.decline();
173
- params.done();
178
+ self.sendEvent("sys_push_blocked");
179
+ self.params.decline();
180
+ self.params.done();
174
181
  });
175
182
  }
176
183
 
177
- function genRandomString() {
178
- var s = [];
179
- for (var i = 0; i < 2; i++) {
184
+ genRandomString() {
185
+ let s = [];
186
+ for (let i = 0; i < 2; i++) {
180
187
  s.push(Math.floor(Math.random() * 0xFFFFFFFF).toString(36));
181
188
  }
182
189
  return s.join("-");
183
190
  }
184
191
 
185
- function getVisitorId() {
186
- var st = window.localStorage;
187
- visitorId = visitorId || st.getItem("visitorId") || getCookie(params.visitorCookie) || genRandomString();
188
- st.setItem("visitorId", visitorId);
189
- setCookie(params.visitorCookie, visitorId, 365);
192
+ getVisitorId() {
193
+ let st = window.localStorage;
194
+ this.visitorId = this.visitorId || st.getItem("visitorId") || this.getCookie(this.params.visitorCookie) || this.genRandomString();
195
+ st.setItem("visitorId", this.visitorId);
196
+ this.setCookie(this.params.visitorCookie, this.visitorId, 365);
190
197
 
191
- return visitorId;
198
+ return this.visitorId;
192
199
  }
193
200
 
194
- function getTimezone() {
201
+ getTimezone() {
195
202
  let timezone = "";
196
203
  try {
197
204
  timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
@@ -202,30 +209,31 @@ function Pushilka(options) {
202
209
  return timezone;
203
210
  }
204
211
 
205
- function getEndpoint(endpoint) {
212
+ getEndpoint(endpoint) {
206
213
  return endpoint + '?'
207
- + 'vid=' + encodeURIComponent(getVisitorId())
208
- + '&sid=' + encodeURIComponent(sessionId)
209
- + '&s=' + encodeURIComponent(params.source.toString())
210
- + '&var1=' + encodeURIComponent(params.var1.toString())
211
- + '&var2=' + encodeURIComponent(params.var2.toString())
212
- + '&var3=' + encodeURIComponent(params.var3.toString())
213
- + '&var4=' + encodeURIComponent(params.var4.toString())
214
- + '&var5=' + encodeURIComponent(params.var5.toString())
215
- + '&var6=' + encodeURIComponent(params.var6.toString())
216
- + '&var7=' + encodeURIComponent(params.var7.toString())
217
- + '&var8=' + encodeURIComponent(params.var8.toString())
218
- + '&var9=' + encodeURIComponent(params.var9.toString())
219
- + '&var10=' + encodeURIComponent(params.var10.toString())
220
- + '&timezone=' + encodeURIComponent(getTimezone());
214
+ + 'vid=' + encodeURIComponent(this.getVisitorId())
215
+ + '&sid=' + encodeURIComponent(this.sessionId)
216
+ + '&s=' + encodeURIComponent(this.params.source.toString())
217
+ + '&var1=' + encodeURIComponent(this.params.var1.toString())
218
+ + '&var2=' + encodeURIComponent(this.params.var2.toString())
219
+ + '&var3=' + encodeURIComponent(this.params.var3.toString())
220
+ + '&var4=' + encodeURIComponent(this.params.var4.toString())
221
+ + '&var5=' + encodeURIComponent(this.params.var5.toString())
222
+ + '&var6=' + encodeURIComponent(this.params.var6.toString())
223
+ + '&var7=' + encodeURIComponent(this.params.var7.toString())
224
+ + '&var8=' + encodeURIComponent(this.params.var8.toString())
225
+ + '&var9=' + encodeURIComponent(this.params.var9.toString())
226
+ + '&var10=' + encodeURIComponent(this.params.var10.toString())
227
+ + '&timezone=' + encodeURIComponent(this.getTimezone());
221
228
  }
222
229
 
223
- function sendSubscriptionToServer(subscription, method) {
224
- var key = subscription.getKey('p256dh');
225
- var token = subscription.getKey('auth');
226
- var contentEncoding = (PushManager.supportedContentEncodings || ['aesgcm'])[0];
230
+ sendSubscriptionToServer(subscription, method) {
231
+ let self = this;
232
+ let key = subscription.getKey('p256dh');
233
+ let token = subscription.getKey('auth');
234
+ let contentEncoding = (PushManager.supportedContentEncodings || ['aesgcm'])[0];
227
235
 
228
- return fetch(getEndpoint(params.endpoint), {
236
+ return fetch(self.getEndpoint(self.params.endpoint), {
229
237
  method: method,
230
238
  body: JSON.stringify({
231
239
  endpoint: subscription.endpoint,
@@ -235,43 +243,44 @@ function Pushilka(options) {
235
243
  })
236
244
  })
237
245
  .then(function () {
238
- params.success();
239
- params.done();
246
+ self.params.success();
247
+ self.params.done();
240
248
  return subscription;
241
249
  })
242
250
  .catch(function () {
243
- params.success();
244
- params.done();
251
+ self.params.success();
252
+ self.params.done();
245
253
  });
246
254
  }
247
255
 
248
- this.ready = function (callback) {
256
+ ready(callback) {
249
257
  if (document.readyState === 'interactive' || document.readyState === 'complete') {
250
258
  callback();
251
259
  } else {
252
260
  document.addEventListener("DOMContentLoaded", callback);
253
261
  }
254
- };
262
+ }
255
263
 
256
- this.run = function () {
257
- this.ready(function () {
258
- if ("showNotification" in ServiceWorkerRegistration.prototype === false) {
264
+ run() {
265
+ let self = this;
266
+ self.ready(function () {
267
+ if (!("showNotification" in ServiceWorkerRegistration.prototype)) {
259
268
  console.debug("Push messaging is not supported.");
260
- sendEvent("push_not_supported");
261
- params.decline();
262
- params.done();
269
+ self.sendEvent("push_not_supported");
270
+ self.params.decline();
271
+ self.params.done();
263
272
  return;
264
273
  }
265
274
 
266
275
  if (Notification.permission === "denied") {
267
276
  console.debug("User has blocked notifications.");
268
- sendEvent("sys_push_blocked");
269
- params.decline();
270
- params.done();
277
+ self.sendEvent("sys_push_blocked");
278
+ self.params.decline();
279
+ self.params.done();
271
280
  return;
272
281
  }
273
282
 
274
- navigator.serviceWorker.register(params.serviceWorker, params.serviceWorkerOptions)
283
+ navigator.serviceWorker.register(self.params.serviceWorker, self.params.serviceWorkerOptions)
275
284
  .then(function () {
276
285
  navigator.serviceWorker.ready
277
286
  .then(function (serviceWorkerRegistration) {
@@ -279,17 +288,17 @@ function Pushilka(options) {
279
288
  })
280
289
  .then(function (subscription) {
281
290
  if (!subscription) {
282
- return params.useDialog ? showDialog() : subscribe();
291
+ return self.params.useDialog ? self.showDialog() : self.subscribe();
283
292
  } else {
284
- return sendSubscriptionToServer(subscription, 'PUT');
293
+ return self.sendSubscriptionToServer(subscription, 'PUT');
285
294
  }
286
295
  });
287
296
  })
288
297
  .catch(function () {
289
- sendEvent("sys_push_subscribe_error");
290
- params.decline();
291
- params.done();
298
+ self.sendEvent("sys_push_subscribe_error");
299
+ self.params.decline();
300
+ self.params.done();
292
301
  });
293
302
  });
294
303
  }
295
- }
304
+ }