From 1a8208c98113c3c1b39a44aeaf9075a6bdb7fba1 Mon Sep 17 00:00:00 2001 From: Bhanu Shukla Date: Sat, 11 Feb 2017 13:15:59 +0530 Subject: [PATCH] push notification code --- images/badge.png | Bin 0 -> 706 bytes images/icon.png | Bin 0 -> 1862 bytes index.html | 22 +++++++- scripts/main.js | 138 +++++++++++++++++++++++++++++++++++++++++++++++ scripts/sw.js | 46 ++++++++++++++++ 5 files changed, 205 insertions(+), 1 deletion(-) create mode 100644 images/badge.png create mode 100644 images/icon.png create mode 100644 scripts/main.js create mode 100644 scripts/sw.js diff --git a/images/badge.png b/images/badge.png new file mode 100644 index 0000000000000000000000000000000000000000..774ae9e7c711734a7daadef16ebf8beb663ae2fa GIT binary patch literal 706 zcmV;z0zLhSP)i{=szN&h=nL3R(hg^ zO>9M?VyA^&ECkU?2nw2yMV=r?$X;&m-g~?Af$iql+0V_)n>{$maU92SoFM>?055=V z;hF~yxtSF?SAk{zXBoI$cR4e_Z&v3QuqS4YjmVD9t&u}B#MD;Mt^zT;>nx~UAZD`8 zf;JS0Y1U~d8!!u80~RUHV))D~U{#f~FYG$QG7s#nl9+8kf0bQly(|NdfUUX9xd<#V zI=%yEa}?7AZZbZu1I=9IG=K+;pZh=~bvXvyAs#n!m^raIU*9jzSK%%33JP8fqsc9Zaa(4@)|clAtRIj>J-OvJ%>>E9qsT=SJ7e zUd67UGYKE8r&DOLxr7DHMQt%)i=V-<+LR|2{+7<=aNpD z+0W7|D9Gt&EJu=hp_1CA3i?M*uL1{CPtxO}l8RQ)y^6^B%W+9}OPfIeRorpR%*v`D zUlbk3aq0x{b%4JYe5vD*{xCr7`#K7GIHK6fwAcjjwm^F=4D)+V?vgeEZ`P30QJn!= oz$M@{@FQFcz=hgYj^osaKiDUlzAkFPXaE2J07*qoM6N<$g85=EN&o-= literal 0 HcmV?d00001 diff --git a/images/icon.png b/images/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..7242e95628e20ec71d90d7fad85bf7781fb8d345 GIT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ORVooN==Nf(&q62VmuMnf-Pvb6FmQL zgWm{BHZY-NfZuBMAWTVA$fhn0S{>fS9uu!X>`p2c9C5vqYqxfj|GT{O=vsMb>AFc{ z=|)K%o3U<^;0dUE%}O^?vqG0A4?sOf5tUng0TfO39bx0+AI&PQ6ji#0=;(%L&vv}* zI4^pTy(5AS2amxN{ylp^Xiue>n@By(7>wLP+dg1gvf^M9{{&=Q{h>I@;~oLCK=1q( zMP(YMIE8$ScBpKck>%#bUAQ)K27Dz6Stj%qy&iB9&^75zv?~vEj8$~10jxB-xP^1ssl e|M)`8J}aNYpam~{)m`Nu4`AKBFb!^@*Zu`#cof0_ literal 0 HcmV?d00001 diff --git a/index.html b/index.html index ad61933..b7ddb31 100755 --- a/index.html +++ b/index.html @@ -18,6 +18,9 @@ + + + @@ -26,11 +29,28 @@

My first pwa

Need Help ! +

+ +

+ + - + + diff --git a/scripts/main.js b/scripts/main.js new file mode 100644 index 0000000..584e3b8 --- /dev/null +++ b/scripts/main.js @@ -0,0 +1,138 @@ +const applicationServerPublicKey = 'BJUILWUXkw_IH40UHBXNSDzf5JMi57_0RxEvdf2fqEcNVlprSYJ7yMZGBCFs0MPs5jtyGlnZFBurhfNWBv-QDjk'; +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; +} + +if ('serviceWorker' in navigator && 'PushManager' in window) { + console.log('Service Worker and Push is supported'); + + navigator.serviceWorker.register('./scripts/sw.js') + .then(function(swReg) { + console.log('Service Worker is registered', swReg); + + swRegistration = swReg; + initialiseUI(); + }) + .catch(function(error) { + console.error('Service Worker Error', error); + }); +} else { + console.warn('Push messaging is not supported'); + pushButton.textContent = 'Push Not Supported'; +} + +var pushButton = document.getElementById("pushButton"); +function initialiseUI() { + 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); + + if (isSubscribed) { + const subscriptionJson = document.querySelector('.js-subscription-json'); + const subscriptionDetails = + document.querySelector('.js-subscription-details'); + subscriptionJson.textContent = JSON.stringify(subscription); + subscriptionDetails.classList.remove('is-invisible'); + console.log('User IS subscribed.'); + } else { + console.log('User is NOT subscribed.'); + } + + updateBtn(); + }); +} + +function updateSubscriptionOnServer(subscription) { + // TODO: Send subscription to application server +console.log(subscription); + 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 applicationServerKey = urlB64ToUint8Array(applicationServerPublicKey); + swRegistration.pushManager.subscribe({ + userVisibleOnly: true, + applicationServerKey: applicationServerKey + }) + .then(function(subscription) { + console.log('User is subscribed.'); + + updateSubscriptionOnServer(subscription); + + isSubscribed = true; + + updateBtn(); + }) + .catch(function(err) { + console.log('Failed to subscribe the user: ', err); + updateBtn(); + }); +} + +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 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(); + }); +} diff --git a/scripts/sw.js b/scripts/sw.js new file mode 100644 index 0000000..6b166b7 --- /dev/null +++ b/scripts/sw.js @@ -0,0 +1,46 @@ +/* +* +* Push Notifications codelab +* Copyright 2015 Google Inc. All rights reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* https://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License +* +*/ + +/* eslint-env browser, serviceworker, es6 */ + +'use strict'; + +self.addEventListener('push', function(event) { + console.log('[Service Worker] Push Received.'); + console.log(`[Service Worker] Push had this data: "${event.data.text()}"`); + + const title = 'WeHelp Notification'; + 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/') + ); +});