Last active
December 29, 2020 13:31
-
-
Save smpnjn/2a4944162afffde64685a5edbe7e3c88 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| const vapidKey = '<<Your Public Vapid Key>>'; | |
| document.getElementById('subscribe').addEventListener('click', async function(e) { | |
| const registration = await navigator.serviceWorker.register('worker.js', {scope: '/'}); | |
| const subscription = await registration.pushManager.subscribe({ | |
| userVisibleOnly: true, | |
| applicationServerKey: urlBase64ToUint8Array(vapidKey) | |
| }); | |
| await fetch('/subscribe', { | |
| method: 'POST', | |
| body: JSON.stringify(subscription), | |
| headers: { | |
| 'content-type': 'application/json' | |
| } | |
| }); | |
| }); | |
| const urlBase64ToUint8Array = function(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; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment