Last active
March 18, 2021 18:07
-
-
Save deyvicode/caee0aaa74d1dbb105b9f80c7fa1d457 to your computer and use it in GitHub Desktop.
A example of register file for a service worker #ServiceWorker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
// 1. verifico que el navegador soporte serviceWorker | |
// 2. registro el service worker | |
// 3. genero la subscripcion ( | |
// - pido permiso al cliente | |
// - genero datos de subscription | |
// - verifico que no haya otra subcripcion anterior | |
// - si no hay subscription guardo sino retorno la existente | |
// ) | |
*/ | |
const PUBLIC_VAPID_KEY = ''; | |
const register = async () => { | |
if ('serviceWorker' in navigator) { | |
const swRegistration = await registerServiceWorker(); | |
await generateSubscription(swRegistration); | |
} else throw new Error('ServiceWorkers are not supported by your browser!'); | |
} | |
const registerServiceWorker = async () => { | |
return await await navigator.serviceWorker.register('/sw.js', { | |
scope: '/' | |
}); | |
} | |
const generateSubscription = async swRegistration => { | |
await window.Notification.requestPermission(); | |
const pushSubscription = await swRegistration.pushManager.getSubscription(); | |
if (!pushSubscription) { | |
const subscription = await swRegistration.pushManager.subscribe({ | |
userVisibleOnly: true, | |
applicationServerKey: urlBase64ToUint8Array(PUBLIC_VAPID_KEY) | |
}); | |
const saved = await saveSubscription(subscription); | |
if (saved) return saved; | |
throw Error('Subscription not saved!'); | |
} else return pushSubscription; | |
} | |
const saveSubscription = async subscription => { | |
const response = await fetch('/notification/subscription/comensal', { | |
method: 'POST', | |
body: JSON.stringify({ | |
other: document.getElementById("other").value, | |
subscription: subscription | |
}), | |
headers: { | |
"Content-Type": "application/json", | |
//"X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr('content') | |
} | |
}); | |
return response.status === 200 ? response.json() : false; | |
} | |
function urlBase64ToUint8Array(base64String) { | |
const padding = '='.repeat((4 - (base64String.length % 4)) % 4); | |
const base64 = (base64String + padding).replace(/\-/g, '+').replace(/_/g, '/'); | |
const rawData = window.atob(base64); | |
const outputArray = new Uint8Array(rawData.length); | |
for (let i = 0; i < rawData.length; ++i) { | |
outputArray[i] = rawData.charCodeAt(i); | |
} | |
return outputArray; | |
} | |
register(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment