Push notifications are the next step and this is an intermediary step to that goal.pull/6/head
parent
954f4355ca
commit
018a7b9a04
@ -0,0 +1,171 @@ |
||||
// main.js
|
||||
|
||||
'use strict'; |
||||
|
||||
// const applicationServerPublicKey = "BNbxGYNMhEIi9zrneh7mqV4oUanjLUK3m+mYZBc62frMKrEoMk88r3Lk596T0ck9xlT+aok0fO1KXBLV4+XqxYM=";
|
||||
const pushButton = document.querySelector('.js-push-btn'); |
||||
|
||||
let isSubscribed = false; |
||||
let swRegistration = null; |
||||
|
||||
function urlB64ToUint8Array(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; |
||||
} |
||||
|
||||
function updateBtn() { |
||||
if (Notification.permission === 'denied') { |
||||
pushButton.textContent = 'Push Messaging Blocked.'; |
||||
pushButton.disabled = true; |
||||
updateSubscriptionOnServer(null); |
||||
return; |
||||
} |
||||
|
||||
if (isSubscribed) { |
||||
pushButton.textContent = 'Disable Push Messaging'; |
||||
} else { |
||||
pushButton.textContent = 'Enable Push Messaging'; |
||||
} |
||||
|
||||
pushButton.disabled = false; |
||||
} |
||||
|
||||
function updateSubscriptionOnServer(subscription) { |
||||
// TODO: Send subscription to application server
|
||||
|
||||
const subscriptionJson = document.querySelector('.js-subscription-json'); |
||||
const subscriptionDetails = |
||||
document.querySelector('.js-subscription-details'); |
||||
|
||||
if (subscription) { |
||||
subscriptionJson.textContent = JSON.stringify(subscription); |
||||
subscriptionDetails.classList.remove('is-invisible'); |
||||
} else { |
||||
subscriptionDetails.classList.add('is-invisible'); |
||||
} |
||||
} |
||||
|
||||
function subscribeUser() { |
||||
const applicationServerPublicKey = localStorage.getItem('applicationServerPublicKey'); |
||||
const applicationServerKey = urlB64ToUint8Array(applicationServerPublicKey); |
||||
swRegistration.pushManager.subscribe({ |
||||
userVisibleOnly: true, |
||||
applicationServerKey: applicationServerKey |
||||
}) |
||||
.then(function(subscription) { |
||||
console.log('User is subscribed.'); |
||||
|
||||
updateSubscriptionOnServer(subscription); |
||||
localStorage.setItem('sub_token',JSON.stringify(subscription)); |
||||
isSubscribed = true; |
||||
|
||||
updateBtn(); |
||||
}) |
||||
.catch(function(err) { |
||||
console.log('Failed to subscribe the user: ', err); |
||||
updateBtn(); |
||||
}); |
||||
} |
||||
|
||||
function unsubscribeUser() { |
||||
swRegistration.pushManager.getSubscription() |
||||
.then(function(subscription) { |
||||
if (subscription) { |
||||
return subscription.unsubscribe(); |
||||
} |
||||
}) |
||||
.catch(function(error) { |
||||
console.log('Error unsubscribing', error); |
||||
}) |
||||
.then(function() { |
||||
updateSubscriptionOnServer(null); |
||||
|
||||
console.log('User is unsubscribed.'); |
||||
isSubscribed = false; |
||||
|
||||
updateBtn(); |
||||
}); |
||||
} |
||||
|
||||
function initializeUI() { |
||||
pushButton.addEventListener('click', function() { |
||||
pushButton.disabled = true; |
||||
if (isSubscribed) { |
||||
unsubscribeUser(); |
||||
} else { |
||||
subscribeUser(); |
||||
} |
||||
}); |
||||
|
||||
// Set the initial subscription value
|
||||
swRegistration.pushManager.getSubscription() |
||||
.then(function(subscription) { |
||||
isSubscribed = !(subscription === null); |
||||
|
||||
updateSubscriptionOnServer(subscription); |
||||
|
||||
if (isSubscribed) { |
||||
console.log('User IS subscribed.'); |
||||
} else { |
||||
console.log('User is NOT subscribed.'); |
||||
} |
||||
|
||||
updateBtn(); |
||||
}); |
||||
} |
||||
|
||||
if ('serviceWorker' in navigator && 'PushManager' in window) { |
||||
console.log('Service Worker and Push is supported'); |
||||
|
||||
navigator.serviceWorker.register("/static/sw.js") |
||||
.then(function(swReg) { |
||||
console.log('Service Worker is registered', swReg); |
||||
|
||||
swRegistration = swReg; |
||||
initializeUI(); |
||||
}) |
||||
.catch(function(error) { |
||||
console.error('Service Worker Error', error); |
||||
}); |
||||
} else { |
||||
console.warn('Push meapplicationServerPublicKeyssaging is not supported'); |
||||
pushButton.textContent = 'Push Not Supported'; |
||||
} |
||||
|
||||
function push_message() { |
||||
console.log("sub_token", localStorage.getItem('sub_token')); |
||||
$.ajax({ |
||||
type: "POST", |
||||
url: "/push_v1/", |
||||
contentType: 'application/json; charset=utf-8', |
||||
dataType:'json', |
||||
data: JSON.stringify({'sub_token':localStorage.getItem('sub_token')}), |
||||
success: function( data ){ |
||||
console.log("success",data); |
||||
}, |
||||
error: function( jqXhr, textStatus, errorThrown ){ |
||||
console.log("error",errorThrown); |
||||
} |
||||
}); |
||||
} |
||||
|
||||
$(document).ready(function(){ |
||||
$.ajax({ |
||||
type:"GET", |
||||
url:'/subscription/', |
||||
success:function(response){ |
||||
console.log("response",response); |
||||
localStorage.setItem('applicationServerPublicKey',response.public_key); |
||||
} |
||||
}) |
||||
}); |
@ -0,0 +1,64 @@ |
||||
// sw.js
|
||||
|
||||
'use strict'; |
||||
|
||||
/* eslint-disable max-len */ |
||||
|
||||
// const applicationServerPublicKey = "BNbxGYNMhEIi9zrneh7mqV4oUanjLUK3m+mYZBc62frMKrEoMk88r3Lk596T0ck9xlT+aok0fO1KXBLV4+XqxYM=";
|
||||
|
||||
/* eslint-enable max-len */ |
||||
|
||||
function urlB64ToUint8Array(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; |
||||
} |
||||
|
||||
self.addEventListener('push', function(event) { |
||||
console.log('[Service Worker] Push Received.'); |
||||
console.log(`[Service Worker] Push had this data: "${event.data.text()}"`); |
||||
|
||||
const title = 'Push Codelab'; |
||||
const options = { |
||||
body: `"${event.data.text()}"`, |
||||
icon: 'images/icon.png', |
||||
badge: 'images/badge.png' |
||||
}; |
||||
|
||||
event.waitUntil(self.registration.showNotification(title, options)); |
||||
}); |
||||
|
||||
self.addEventListener('notificationclick', function(event) { |
||||
console.log('[Service Worker] Notification click Received.'); |
||||
|
||||
event.notification.close(); |
||||
|
||||
event.waitUntil( |
||||
clients.openWindow('https://developers.google.com/web/') |
||||
); |
||||
}); |
||||
|
||||
self.addEventListener('pushsubscriptionchange', function(event) { |
||||
console.log('[Service Worker]: \'pushsubscriptionchange\' event fired.'); |
||||
const applicationServerPublicKey = localStorage.getItem('applicationServerPublicKey'); |
||||
const applicationServerKey = urlB64ToUint8Array(applicationServerPublicKey); |
||||
event.waitUntil( |
||||
self.registration.pushManager.subscribe({ |
||||
userVisibleOnly: true, |
||||
applicationServerKey: applicationServerKey |
||||
}) |
||||
.then(function(newSubscription) { |
||||
// TODO: Send to application server
|
||||
console.log('[Service Worker] New subscription: ', newSubscription); |
||||
}) |
||||
); |
||||
}); |
Loading…
Reference in new issue