Created
December 11, 2017 01:15
-
-
Save lachlanagnew/ba77f6dbc2fd5675dd187626d3b0ddf3 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
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