Merge pull request 'Added service worker js and push.js' (#112) from ranjith-dev into master
All checks were successful
Scan for leaked secrets using Kingfisher / kingfisher-secrets-scan (push) Successful in 11s
All checks were successful
Scan for leaked secrets using Kingfisher / kingfisher-secrets-scan (push) Successful in 11s
Reviewed-on: #112
This commit was merged in pull request #112.
This commit is contained in:
43
public/js/push.js
Normal file
43
public/js/push.js
Normal file
@@ -0,0 +1,43 @@
|
||||
async function registerPush() {
|
||||
try {
|
||||
console.log("Registering for push notifications");
|
||||
|
||||
if (!('serviceWorker' in navigator)) {
|
||||
console.error("ServiceWorker not supported");
|
||||
return;
|
||||
}
|
||||
|
||||
const permission = await Notification.requestPermission();
|
||||
console.log("Permission:", permission);
|
||||
|
||||
if (permission !== 'granted') {
|
||||
console.warn("Notification permission denied");
|
||||
return;
|
||||
}
|
||||
|
||||
const registration = await navigator.serviceWorker.register('/sw.js');
|
||||
console.log("SW registered:", registration);
|
||||
|
||||
const subscription = await registration.pushManager.subscribe({
|
||||
userVisibleOnly: true,
|
||||
applicationServerKey: vapidKey
|
||||
});
|
||||
|
||||
console.log("Subscription created:", subscription);
|
||||
|
||||
const res = await fetch('/push/subscribe', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-CSRF-TOKEN': csrfToken
|
||||
},
|
||||
body: JSON.stringify(subscription)
|
||||
});
|
||||
|
||||
console.log("Server response:", await res.text());
|
||||
|
||||
alert("Push enabled ✅");
|
||||
} catch (e) {
|
||||
console.error("Push registration failed ❌", e);
|
||||
}
|
||||
}
|
||||
10
public/service-worker.js
Normal file
10
public/service-worker.js
Normal file
@@ -0,0 +1,10 @@
|
||||
self.addEventListener('push', function (event) {
|
||||
const data = event.data.json();
|
||||
event.waitUntil(
|
||||
self.registration.showNotification(data.title, {
|
||||
body: data.body,
|
||||
icon: data.icon,
|
||||
data: data.data
|
||||
})
|
||||
);
|
||||
});
|
||||
Reference in New Issue
Block a user