Last active
January 6, 2020 17:08
-
-
Save charisTheo/6efe941fccd87c8317853e7e525a62e1 to your computer and use it in GitHub Desktop.
Register Service Worker on the front-end and request Push Permission
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
| if ('serviceWorker' in navigator) { // || 'ServiceWorker' in window | |
| sw(); | |
| } | |
| function sw() { | |
| const registration = navigator.serviceWorker.register('/sw.js', {scope: '/'}) | |
| .then(function(_registration) { | |
| console.log('Registration succeeded. Scope is ' + _registration.scope); | |
| // request push notification permission only when user clicks the notification button as a good practise | |
| $('#notifications-button').on("click", function() { | |
| // check permissions if notifications icon is clicked | |
| _registration.pushManager.permissionState({userVisibleOnly: true}).then(permission => { | |
| // Possible values are 'prompt', 'denied', or 'granted' | |
| if (permission === "prompt") { | |
| // request permission only when user has not either denied or accepted notifications | |
| requestPushPermission(_registration); | |
| } | |
| }).catch(() => { | |
| // error | |
| }); | |
| }); | |
| }).catch(function(error) { | |
| console.log('Registration failed with ' + error); | |
| }); | |
| } | |
| function requestPushPermission(registration) { | |
| registration.pushManager.subscribe({ | |
| userVisibleOnly: true, | |
| applicationServerKey: urlBase64ToUint8Array(PUBLIC_VAPID_KEY) // PUBLIC_VAPID_KEY is created by a push manager on the back-end | |
| }).then(function(subscription) { | |
| fetch('/subscribe', { // custom route for handling and saving the push subscription of the user | |
| method: 'POST', | |
| body: JSON.stringify(subscription), | |
| headers: { | |
| 'content-type': 'application/json' | |
| } | |
| }); | |
| console.log("user subscribed"); | |
| }); | |
| } | |
| 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; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment