-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathprofile_webpush_controller.js
More file actions
117 lines (104 loc) · 3.83 KB
/
profile_webpush_controller.js
File metadata and controls
117 lines (104 loc) · 3.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
static values = {
vapidPublic: String,
}
static targets = ["checkbox"]
connect() {
console.log('webpush connected!');
if ('serviceWorker' in navigator && 'PushManager' in window) {
navigator.serviceWorker.ready.then(registration => {
registration.pushManager.getSubscription().then(subscription => {
if (subscription) {
this.checkboxTarget.style.disabled = true;
this.checkboxTarget.classList.add('disabled');
}
}).catch(error => {
console.error('Error checking subscription:', error);
});
});
}
}
setupPushNotifications() {
if ("Notification" in window) {
Notification.requestPermission().then((permission) => {
if (permission === "granted") {
this.registerAndSubscribe();
} else {
console.warn("User rejected to allow notifications.");
}
});
} else {
console.warn("Push notifications not supported.");
}
}
registerAndSubscribe() {
const applicationServerKey = this.urlBase64ToUint8Array(this.vapidPublicValue);
navigator.serviceWorker.register("/service-worker.js", {scope: "./" })
.then((registration) => {
console.log('Service Worker registered successfully:', registration);
return navigator.serviceWorker.ready;
})
.then((serviceWorkerRegistration) => {
return serviceWorkerRegistration.pushManager.getSubscription()
.then((existingSubscription) => {
if (!existingSubscription) {
return serviceWorkerRegistration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: applicationServerKey
});
}
return existingSubscription;
});
})
.then((subscription) => {
const endpoint = subscription.endpoint;
const p256dh = btoa(String.fromCharCode.apply(null, new Uint8Array(subscription.getKey('p256dh'))));
const auth = btoa(String.fromCharCode.apply(null, new Uint8Array(subscription.getKey('auth'))));
return fetch('/push_subscriptions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
},
body: JSON.stringify({
subscription: {
endpoint: endpoint,
p256dh: p256dh,
auth: auth
}
})
}).then(response => {
if (response.ok) {
console.log("Subscription successfully saved on the server.");
localStorage.setItem('block-webpush-modal', 'true');
const modal = document.querySelector('.webpush-modal');
if (modal) {
modal.style.display = 'none';
}
this.checkboxTarget.style.disabled = true;
this.checkboxTarget.classList.add('disabled');
} else {
throw new Error(`Server responded with status: ${response.status}`);
}
});
})
.catch(error => {
console.error('Service Worker registration or subscription failed:', error);
alert('Failed to enable push notifications. Please try again later.');
});
}
urlBase64ToUint8Array(base64String) {
var padding = '='.repeat((4 - base64String.length % 4) % 4);
var base64 = (base64String + padding)
.replace(/\-/g, '+')
.replace(/_/g, '/');
var rawData = window.atob(base64);
var outputArray = new Uint8Array(rawData.length);
for (var i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
}