Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added images/badge.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added images/icon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
22 changes: 21 additions & 1 deletion index.html
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@
<link rel="apple-touch-icon" href="./images/icons/icon-152x152.png">
<meta name="msapplication-TileImage" content="./images/icons/icon-144x144.png">
<meta name="msapplication-TileColor" content="#2F3BA2">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://code.getmdl.io/1.2.1/material.indigo-pink.min.css">
<script defer src="https://code.getmdl.io/1.2.1/material.min.js"></script>
</head>

<body>
Expand All @@ -26,11 +29,28 @@ <h1 class="header__title">My first pwa</h1>
<div class="g-signin2" data-onsuccess="onSignIn" data-theme="dark"></div>
<a href="./needHelp.html">Need Help !</a>

<p>
<button disabled id="pushButton" class="js-push-btn mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect">
Enable Push Messaging
</button>
</p>
<section class="subscription-details js-subscription-details is-invisible">
<p>Once you've subscribed your user, you'd send their subscription to your
server to store in a database so that when you want to send a message
you can lookup the subscription and send a message to it.</p>
<p>To simplify things for this code lab copy the following details
into the <a href="https://web-push-codelab.appspot.com/">Push Companion
Site</a> and it'll send a push message for you, using the application
server keys on the site - so make sure they match.</p>
<pre><code class="js-subscription-json"></code></pre>
</section>

<script src="https://apis.google.com/js/platform.js" async defer></script>
<script src="./scripts/jquery-3.1.1.min.js"></script>
<script src="./scripts/authenticate.js"></script>
<script src="./scripts/app.js" async></script>
</script>
<script defer src="https://code.getmdl.io/1.2.1/material.min.js"></script>
<script src="./scripts/main.js"></script>
</body>

</html>
138 changes: 138 additions & 0 deletions scripts/main.js
Original file line number Diff line number Diff line change
@@ -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();
});
}
46 changes: 46 additions & 0 deletions scripts/sw.js
Original file line number Diff line number Diff line change
@@ -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/')
);
});