43 lines
1.6 KiB
JavaScript
43 lines
1.6 KiB
JavaScript
// Please see documentation at https://docs.microsoft.com/aspnet/core/client-side/bundling-and-minification
|
|
// for details on configuring this project to bundle and minify static web assets.
|
|
|
|
if ('serviceWorker' in navigator) {
|
|
window.addEventListener('load', function () {
|
|
navigator.serviceWorker.register('/service-worker.js')
|
|
.then(function (registration) {
|
|
console.log('✅ Service Worker registrerad med scope:', registration.scope);
|
|
subscribeToPush().catch(console.error);
|
|
})
|
|
.catch(function (error) {
|
|
console.log('❌ Service Worker-registrering misslyckades:', error);
|
|
});
|
|
});
|
|
}
|
|
|
|
async function subscribeToPush() {
|
|
const registration = await navigator.serviceWorker.ready;
|
|
const publicVapidKey = await fetch('/api/push/vapid-public-key').then(r => r.text());
|
|
|
|
const subscription = await registration.pushManager.subscribe({
|
|
userVisibleOnly: true,
|
|
applicationServerKey: urlBase64ToUint8Array(publicVapidKey)
|
|
});
|
|
|
|
await fetch('/api/push/subscribe', {
|
|
method: 'POST',
|
|
body: JSON.stringify(subscription),
|
|
headers: { 'Content-Type': 'application/json' }
|
|
});
|
|
|
|
console.log('✅ Push-prenumeration skickad');
|
|
}
|
|
|
|
|
|
// utility för att konvertera nyckeln
|
|
function urlBase64ToUint8Array(base64String) {
|
|
const padding = '='.repeat((4 - base64String.length % 4) % 4);
|
|
const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');
|
|
const raw = atob(base64);
|
|
return new Uint8Array([...raw].map(char => char.charCodeAt(0)));
|
|
}
|