0% found this document useful (0 votes)
18 views1 page

Service Worker Push Notifications Setup

The document outlines a JavaScript implementation for registering a service worker and requesting notification permissions. It checks for support of service workers and push notifications, subscribes the user to push notifications, and sends the subscription to a server for storage. Additionally, it includes a helper function to convert a VAPID public key from base64 format to a Uint8Array.

Uploaded by

jidangamer7
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views1 page

Service Worker Push Notifications Setup

The document outlines a JavaScript implementation for registering a service worker and requesting notification permissions. It checks for support of service workers and push notifications, subscribes the user to push notifications, and sends the subscription to a server for storage. Additionally, it includes a helper function to convert a VAPID public key from base64 format to a Uint8Array.

Uploaded by

jidangamer7
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

if ('serviceWorker' in navigator && 'PushManager' in window) {

[Link]('[Link]')
.then(registration => {
[Link]('Service Worker registered');

// Minta izin notifikasi


return [Link]()
.then(permission => {
if (permission !== 'granted') {
throw new Error('Izin notifikasi ditolak');
}
return registration;
});
})
.then(registration => {
// Daftarkan push subscription
return [Link]()
.then(async subscription => {
if (subscription) return subscription;

const response = await fetch('/vapidPublicKey');


const vapidPublicKey = await [Link]();
const convertedKey = urlBase64ToUint8Array(vapidPublicKey);

return [Link]({
userVisibleOnly: true,
applicationServerKey: convertedKey
});
});
})
.then(subscription => {
// Kirim subscription ke server untuk simpan
fetch('/saveSubscription', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: [Link](subscription)
});
})
.catch([Link]);
} else {
[Link]('Service Worker atau Push Manager tidak didukung');
}

// Fungsi helper untuk konversi key VAPID


function urlBase64ToUint8Array(base64String) {
const padding = '='.repeat((4 - [Link] % 4) % 4);
const base64 = (base64String + padding)
.replace(/\-/g, '+')
.replace(/_/g, '/');

const rawData = [Link](base64);


const outputArray = new Uint8Array([Link]);

for(let i = 0; i < [Link]; ++i){


outputArray[i] = [Link](i);
}
return outputArray;
}

You might also like