Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Vasu: pwa add home screen shortcut and push msgs #5

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
2 changes: 2 additions & 0 deletions app/components/head.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ export const Head = ({}) => {
<link rel="preconnect" href="http://longwallpapers.com"/>
<link rel="preload" href="http://longwallpapers.com/Desktop-Wallpaper/marvel-avengers-wallpapers-high-definition-For-Desktop-Wallpaper.jpg" as="image"/>
<link rel="preload" href="https://img00.deviantart.net/bd6a/i/2013/220/e/2/thor__the_dark_world__hi_res_textless_banner__by_phetvanburton-d6hb9q0.jpg" as="image"/>
<link rel="manifest" href="/manifest.json" />
<meta name="theme-color" content="red"/>
</head>
);
}
3 changes: 3 additions & 0 deletions app/components/navigation.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ export class Navigation extends React.Component {
render() {
return(
<section className="section slideInUp animated">
<button id="btnPush"></button>
<div className="js-subscription-json"></div>
<div className="js-subscription-details is-invisible"></div>
<h2 className="section-heading">New Recruits</h2>
<h3 className="section-sub-title">Click on names to reveal the complete identity of a recruit</h3>
<div className="jumbotron">
Expand Down
144 changes: 143 additions & 1 deletion app/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,146 @@ import React from 'react';
import {hydrate} from "react-dom";
import App from "./components/app";

hydrate(<App data={window.dataLayer}/>, document.getElementById('root'));
hydrate(<App data={window.dataLayer}/>, document.getElementById('root'));


if(window) {
let isSubscribed = false;
let swRegistration;

//button to enable disablew push notifications
const pushButton = document.getElementById("btnPush");
//public key from https://web-push-codelab.glitch.me/
const applicationServerPublicKey = "BIZC9uQDm0U97k4QxrElAp6yKACUeRltH9nR5isFc81g7ORYg9R9yKSrdT-gEAPJOGMak7m5L2sNRw1HUV2G2XI";

//register service worker
navigator.serviceWorker && navigator.serviceWorker.register('./sw.js').then(function(registration) {
console.log('Excellent, registered with scope: ', registration.scope);
swRegistration = registration;
setSubscriptionBtnText();
});


function setSubscriptionBtnText() {
// Set the initial subscription value
swRegistration.pushManager.getSubscription()
.then(function(subscription) {
isSubscribed = !(subscription === null);

if (isSubscribed) {
console.log('User IS subscribed.');
} else {
console.log('User is NOT subscribed.');
subscribeUser();
}

updateBtn();
});
}

function subscribeUser() {
const applicationServerKey = urlB64ToUint8Array(applicationServerPublicKey);
swRegistration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: applicationServerKey
})
.then(function(subscription) {
console.log('User is subscribed.');
//send subscruption end points to BE in future
updateSubscriptionOnServer(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 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 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 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;
}

//event to prompt user to add to home screen
window.addEventListener('beforeinstallprompt', (e) => {
e.prompt();
});

//callback event for sub scribe/unscribe for notification
pushButton.addEventListener('click', function() {
pushButton.disabled = true;
if (isSubscribed) {
unsubscribeUser();
} else {
subscribeUser();
}
});


}
Loading