Skip to content

Instantly share code, notes, and snippets.

@lachlanagnew
Last active June 6, 2019 14:20
Show Gist options
  • Select an option

  • Save lachlanagnew/30759d6d1936c80875ab9a8a334816fa to your computer and use it in GitHub Desktop.

Select an option

Save lachlanagnew/30759d6d1936c80875ab9a8a334816fa to your computer and use it in GitHub Desktop.
Subscribe and register service worker
//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!'
});
}
@mparramont

Copy link
Copy Markdown

Line 46:

 $.post('/sendkeys, {

should be

 $.post('/sendkeys`, {

right? :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment