Skip to content

Commit

Permalink
Updated with custom buttons in notfication
Browse files Browse the repository at this point in the history
  • Loading branch information
gokulkrishh committed Sep 1, 2016
1 parent b23101a commit 261e923
Show file tree
Hide file tree
Showing 5 changed files with 144 additions and 72 deletions.
14 changes: 13 additions & 1 deletion css/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ button {
color: #fff;
border-radius: 2px;
margin: 0 auto -5px;
display: block;
display: inline-block;
cursor: pointer;
outline: 0;
box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.38);
Expand All @@ -220,6 +220,12 @@ button:active {
box-shadow: none;
}

button:disabled {
background: #ccc;
color: #000;
cursor: not-allowed;
}

.custom-checkbox {
display: inline-block;
position: relative;
Expand Down Expand Up @@ -302,3 +308,9 @@ button:active {
padding-left: 15px;
padding-bottom: 15px;
}

.disable-log {
margin-left: 20px;
user-select: none;
-webkit-user-select: none;
}
14 changes: 8 additions & 6 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,13 @@
<p class="custom-button">
<input id="turn-on-notification" type="checkbox" hidden="hidden" class="custom-input" data-checked="">
<label for="turn-on-notification" class="custom-checkbox"></label>
Enable Push Notification
<button class="btn-notification" id="send-push" disabled>Send Push Notification</button>
<label class="disable-log" for="disable-log">
<input type="checkbox" id="disable-log" class="disable-console-log">
Disable console log
</label>
</p>

<button class="btn-notification hide" id="send-push">Send Push Notification</button>

<div class="card-container">
<div class="card">
<p class="card-title">Bangalore, In</p>
Expand All @@ -70,12 +72,12 @@
<script type="text/javascript">
//If serviceWorker supports, then register it.
if ("serviceWorker" in navigator) {
navigator.serviceWorker.register("./serviceWorker.js")
navigator.serviceWorker.register('./serviceWorker.js', { scope: "./" }) //setting scope of sw
.then(function (registration) {
console.log("SW registered");
console.log('%c service worker is registered ', 'background: #DFF2BF; color: #4F8A10; font-size: 13px;');
})
.catch(function (error) {
console.error("SW failed", error);
console.error('service worker failed ', 'background: #FFBABA; color: #D8000C; font-size: 13px;', error);
});
}
</script>
Expand Down
39 changes: 34 additions & 5 deletions js/app.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,37 @@
'use strict';

var apiKey = '428a20d6f31803d62bc3d29c0eff0937';
var spinnerElement = document.querySelector('.spinner');
var spinnerClassList = spinnerElement.classList;
// var spinnerElement = document.querySelector('.spinner');
var headerElement = document.querySelector('header');
var menuIconElement = document.querySelector('.header-icon');
var menuElement = document.querySelector('.menu');
var menuOverlayElement = document.querySelector('.menu-overlay');
var disableLogElement = document.querySelector('.disable-console-log');

//Listen to disable log checkbox
disableLogElement.addEventListener("change", function (event) {
if (event.target.checked) {
localStorage.setItem("disable-log", true);
disableLog();
}
else {
localStorage.removeItem("disable-log");
console = window.console;
}
}, false);

//To disable console log
function disableLog() {
console.log = function() {};
}

//To show/hide loading indicator
function toggleSpinner() {
if (spinnerClassList.contains('hide')) {
spinnerClassList.remove('hide');
if (spinnerElement.classList.contains('hide')) {
spinnerElement.classList.remove('hide');
}
else {
spinnerClassList.add('hide');
spinnerElement.classList.add('hide');
}
}

Expand Down Expand Up @@ -45,6 +62,18 @@ menuIconElement.addEventListener("click", showMenu, false);
menuOverlayElement.addEventListener("click", hideMenu, false);

(function () {

if (localStorage.getItem("disable-log")) {
console.log = function() {};
disableLogElement.checked = true;
}

//If `serviceWorker` is registered and ready
navigator.serviceWorker.ready
.then(function (registration) {
isPushSupported(registration); //To check push is supported and enabled
})

//Check network status
window.addEventListener('online', updateNetworkStatus, false);
window.addEventListener('offline', updateNetworkStatus, false);
Expand Down
101 changes: 56 additions & 45 deletions js/main.js
Original file line number Diff line number Diff line change
@@ -1,109 +1,121 @@
//Push notification button
var btn = document.getElementById("turn-on-notification");
var notificationBtnElement = document.getElementById('turn-on-notification');
var pushBtnElement = document.getElementById("send-push");

//Tokens
var apiKey = "AIzaSyCjrU5SqotSg2ybDLK_7rMMt9Rv0dMusvY"; //replace with your own key
var gcmURL = "https://android.googleapis.com/gcm/send";
//API key & GCM Token
var apiKey = 'AIzaSyCjrU5SqotSg2ybDLK_7rMMt9Rv0dMusvY'; //replace with your own key
var gcmURL = 'https://android.googleapis.com/gcm/send';

//To check push notification support
function isPushNotification(serviceWorkerRegistration) {
serviceWorkerRegistration.pushManager.getSubscription()
//To check `push notification` is supported
function isPushSupported(swRegistration) {

//To check if `push notification` is denied by user or not
if (Notification.permission === 'denied') {
console.warn('User has blocked push notification.');
return;
}

//Check `push notification` is supported or not
if (!('PushManager' in window)) {
console.warn('Push notification isn\'t supported in your browser.');
return;
}

//Get `push notification` subscription
swRegistration.pushManager.getSubscription()
.then(function (subscription) {
console.log("Push Notification Status: ", subscription);
//If already access granted, change status and send subscription
//If already access granted, enable push button status
if (subscription) {
changeStatus(true);
changePushStatus(true);
}
else {
changeStatus(false);
changePushStatus(false);
}
})
.catch(function (error) {
console.error(error);
console.error("Error occurred while enable push ", error);
});
}

//To subscript push notification
function subscribe() {
//To subscribe `push notification`
function subscribePush() {
navigator.serviceWorker.ready
.then(function(registration) {
if (!registration.pushManager) {
alert("Your browser doesn't support push notifications");
alert('Your browser doesn\'t support push notification.');
return;
}

registration.pushManager.subscribe({
userVisibleOnly: true //To always show notification when received
userVisibleOnly: true //Always show notification when received
})
.then(function (subscription) {
console.log("Successfully subscribed: ", subscription);
changeStatus(true);
console.log('%c Push notification subscribed ', 'background: #DFF2BF; color: #4F8A10; font-size: 13px;');
changePushStatus(true);
})
.catch(function (error) {
console.error(error);
console.log('Push notification subscription error: ', error);
})
})
}

//To unsubscribe push notification
function unsubscribe() {
//To unsubscribe `push notification`
function unsubscribePush() {
navigator.serviceWorker.ready
.then(function(registration) {
registration.pushManager.getSubscription()
.then(function (subscription) {
//If not push subscription, then return
//If no `push subscription`, then return
if(!subscription) {
console.error("Unable to unregister from push notification");
console.error('Unable to unregister push notification.');
return;
}

//Unsubscribe
//Unsubscribe `push notification`
subscription.unsubscribe()
.then(function () {
console.log("Successfully unsubscribed");
changeStatus(false);
console.log('%c Push notification unsubscribed ', 'background: #FEEFB3; color: #9F6000; font-size: 13px');
changePushStatus(false);
})
.catch(function (error) {
console.error(error);
});
})
.catch(function (error) {
console.error("Failed to unsubscribe push notification");
console.error('Failed to unsubscribe push notification.');
});
})
}

var notificationBtn = document.querySelector(".btn-notification");

//To change status
function changeStatus(status) {
btn.dataset.checked = status;
btn.checked = status;
function changePushStatus(status) {
notificationBtnElement.dataset.checked = status;
notificationBtnElement.checked = status;
if (status) {
notificationBtn.classList.remove("hide");
pushBtnElement.removeAttribute("disabled");
}
else {
notificationBtn.classList.add("hide");
pushBtnElement.setAttribute("disabled", true);
}
}

//Click event for subscribe btn
btn.addEventListener("click", function () {
var isBtnChecked = (btn.dataset.checked === "true");
//Click event for subscribe notificationBtnElement
notificationBtnElement.addEventListener('click', function () {
var isBtnChecked = (notificationBtnElement.dataset.checked === 'true');
if (isBtnChecked) {
unsubscribe();
unsubscribePush();
}
else {
subscribe();
subscribePush();
}
});

//To generate curl command to send push notification
function curlCommand(subscription) {
var temp = subscription.endpoint.split("/");
var temp = subscription.endpoint.split('/');
var endpoint = temp[temp.length - 1];
var curlCommand = 'curl --header "Authorization: key=' + apiKey + '" --header Content-Type:"application/json" ' + gcmURL + ' -d "{\\"registration_ids\\":[\\"' + endpoint + '\\"]}"';
console.log("%ccurl command: ", "background: #000; color: #fff; font-size: 16px;");
console.log("%c Use curl command to send push notification: ", "background: #000; color: #fff; font-size: 13px;");
console.log(curlCommand);
}

Expand Down Expand Up @@ -132,8 +144,7 @@ function sendPushNotification(subscription) {
})
}

//To send push notification
var pushBtn = document.getElementById("send-push");
pushBtn.addEventListener("click", function () {
//To send `push notification`
pushBtnElement.addEventListener("click", function () {
sendPushNotification();
});
}, false);
48 changes: 33 additions & 15 deletions serviceWorker.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ var files = [

//Adding `install` event listener
self.addEventListener('install', function (event) {
console.log('Event: Install');
console.log('%c Event: Install ', 'background: #FEEFB3; color: #9F6000; font-size: 13px;');

event.waitUntil(
caches.open(cacheName)
Expand All @@ -47,7 +47,7 @@ self.addEventListener('install', function (event) {
self.addEventListener('fetch', function (event) {
var request = event.request;

console.log('Event: Fetch');
console.log('%c Event: Fetch ', 'background: #FEEFB3; color: #9F6000; font-size: 13px;');

//Tell the browser to wait for network request and respond with below
event.respondWith(
Expand Down Expand Up @@ -79,7 +79,7 @@ self.addEventListener('fetch', function (event) {

//Adding `activate` event listener
self.addEventListener('activate', function (event) {
console.log('Event: Activate');
console.log('%c Event: Activate ', 'background: #FEEFB3; color: #9F6000; font-size: 13px;');

//Active Service Worker to set itself as the active on current client and all other active clients.
return self.clients.claim();
Expand All @@ -91,13 +91,18 @@ self.addEventListener('activate', function (event) {

//Adding `push` event listener
self.addEventListener('push', function(event) {
console.log('Event: Push', event);
console.log('%c Event: Push ', 'background: #FEEFB3; color: #9F6000; font-size: 13px;');

var title = 'Push notification demo';
var body = {
'body': 'You have received a notification',
'body': 'click to return to application',
'tag': 'demo',
'icon': '/images/icons/apple-touch-icon.png'
'icon': '/images/icons/apple-touch-icon.png',
//Custom actions buttons
'actions': [
{ "action": "yes", "title": "I ♥ this app!"},
{ "action": "no", "title": "I don\'t like this app"}
]
};

event.waitUntil(self.registration.showNotification(title, body));
Expand All @@ -109,24 +114,37 @@ self.addEventListener('push', function(event) {

//Adding `notification` click event listener
self.addEventListener('notificationclick', function(event) {
console.log('Notification clicked ', event);
//Listen to custom actions buttons
if (event.action === 'yes') {
console.log('%c I ♥ this app! ', 'background: #000; color: #fff');
}
else if (event.action === 'no') {
console.log('%c I don\'t like this app ', 'background: #000; color: #fff');
}

//To open the app after clicking notification
event.waitUntil(
clients.matchAll({
type: 'window'
})
.then(function(clientList) {
console.log("clientList -->", clientList);
for (var i = 0; i < clientList.length; i++) {
var client = clientList[i];
console.log("client", client);
if (client.url == '/' && 'focus' in client) {
.then(function(clients) {
for (var i = 0; i < clients.length; i++) {
var client = clients[i];
//If site is opened, focus to the site
if ('focus' in client && !client.focused) {
event.notification.close();
return client.focus();
}
//If site is not opened, open in new tab
if (clients.openWindow) {
return clients.openWindow('/');
}
}
})

event.notification.close();
event.notification.close(); //Close the notification
})
.catch(function (err) {
console.log(err);
})
);
});

0 comments on commit 261e923

Please sign in to comment.