Last active
June 6, 2019 14:20
-
-
Save lachlanagnew/30759d6d1936c80875ab9a8a334816fa to your computer and use it in GitHub Desktop.
Subscribe and register service worker
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
| //app/views/content/index.html.erb | |
| javascript: | |
| var vapidPublicKey = new Uint8Array(#{Base64.urlsafe_decode64($vapid_public).bytes}); | |
| function checkNotifs(obj){ | |
| if (!("Notification" in window)) { //1 | |
| console.error("This browser does not support desktop notification"); | |
| } | |
| // Let's check whether notification permissions have already been granted | |
| else if (Notification.permission === "granted") { //2 | |
| console.log("Permission to receive notifications has been granted"); | |
| getKeys(); | |
| } | |
| // Otherwise, we need to ask the user for permission | |
| else if (Notification.permission !== 'denied') { //3 | |
| Notification.requestPermission(function (permission) { | |
| // If the user accepts, let's create a notification | |
| if (permission === "granted") { //4 | |
| console.log("Permission to receive notifications has been granted"); | |
| getKeys(); | |
| } | |
| }); | |
| } | |
| } | |
| function getKeys(){ | |
| navigator.serviceWorker.register('/serviceworker.js', {scope: './'}) //5 | |
| .then(function(registration) { | |
| return registration.pushManager.getSubscription() | |
| .then(function(subscription) { | |
| if (subscription) { | |
| return subscription; | |
| } | |
| return registration.pushManager.subscribe({ //6 | |
| userVisibleOnly: true, | |
| applicationServerKey: vapidPublicKey | |
| }); | |
| }); | |
| }).then(function(subscription) { | |
| sendKeys(subscription.toJSON()) //7 | |
| }); | |
| } | |
| function sendKeys(subscription){ | |
| $.post('/sendkeys, { | |
| subscription: subscription, | |
| message: 'You clicked a button!' | |
| }); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Line 46:
should be
right? :)