Skip to content

Commit

Permalink
Added push notification
Browse files Browse the repository at this point in the history
  • Loading branch information
gokulkrishh committed Mar 3, 2016
1 parent 77ddafe commit 522e66c
Show file tree
Hide file tree
Showing 6 changed files with 169 additions and 110 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@
3. In terminal, type

```
$ python -m SimpleHTTPServer 3000
$ npm install && npm start
```

4. In browser, open [http://localhost:3000](localhost:3000)
Expand All @@ -69,7 +69,7 @@
$ npm install --global manifest-json
```
- [x] - Push notification - Get curl command in console to send notification
- [x] - Push notification
- [ ] - Background Sync - In progress
Expand Down
7 changes: 5 additions & 2 deletions js/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,10 @@ $(function () {
});


//To find device is online/offline
//Online/offline event cb
/*
To find device is online or offline
*/

function onLineStatus(event) {
console.log("Online: ", navigator.onLine);
if (navigator.onLine) {
Expand All @@ -97,6 +99,7 @@ $(function () {
}
}

//Event listener for offline/online events
window.addEventListener("online", onLineStatus);
window.addEventListener("offline", onLineStatus);
});
133 changes: 58 additions & 75 deletions js/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@
if ("serviceWorker" in navigator) {
navigator.serviceWorker
.register("./serviceWorker.js") //Point to serviceWorker file
.then(function (serviceWorkerRegistration) {
console.log("serviceWorker is registered");
.then(function (registration) {
console.log("Service Worker is registered");
document.getElementById("sw-register-state").textContent = "✓";

//To check support for push notifications
isPushNotification(serviceWorkerRegistration);
isPushNotification(registration);
})
.catch(function (error) {
console.log("Failed to register serviceWorker");
console.error("Failed to register service worker");
document.getElementById("sw-register-state").textContent = "✕"; //Failed to register
});
}
Expand All @@ -20,14 +20,12 @@ var btn = document.getElementById("turn-on-notification");

//Tokens
var apiKey = "AIzaSyCjrU5SqotSg2ybDLK_7rMMt9Rv0dMusvY";
var pushManager;
var gcmURL = "https://android.googleapis.com/gcm/send";
var endpoint;

//To check push notification support
function isPushNotification(serviceWorkerRegistration) {
if (!serviceWorkerRegistration.pushManager) {
alert("Update chrome browser to support push notifications");
alert("Update your to support push notifications");
return;
}

Expand All @@ -43,60 +41,52 @@ function isPushNotification(serviceWorkerRegistration) {
}
})
.catch(function (error) {
console.log(error);
console.error(error);
});
}

//To subscript push notification
function subscribeNotification() {
function subscribe() {
navigator.serviceWorker.ready
.then(function(serviceWorkerRegistration) {
pushManager = serviceWorkerRegistration.pushManager;

pushManager.subscribe({
.then(function(registration) {
registration.pushManager.subscribe({
userVisibleOnly: true //To always show notification when received
})
.then(function (subscription) {
console.log("Successfully subscribed: ", subscription);
console.log("Endpoint: ", subscription.endpoint);

var endpointTemp = subscription.endpoint.split("/");
endpoint = endpointTemp[endpointTemp.length - 1];
localStorage.setItem("endpoint", JSON.stringify(endpoint));
logCurlCommand(endpoint);
curlCommand(subscription);
changeStatus(true);
})
.catch(function (error) {
console.log(error);
console.error(error);
})
})
}

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

pushSubscription.unsubscribe()
.then(function () {
console.log("Successfully unsubscribed");
endpoint = null;
localStorage.removeItem("endpoint");
changeStatus(false);
})
.catch(function (error) {
console.log(error);
});
//Unsubscribe
subscription.unsubscribe()
.then(function () {
console.log("Successfully unsubscribed");
changeStatus(false);
})
.catch(function (error) {
console.error(error);
});
})
.catch(function (error) {
console.log("Failed to unsubscribe push notification");
console.error("Failed to unsubscribe push notification");
});
})
}
Expand All @@ -117,57 +107,50 @@ function changeStatus(status) {
btn.addEventListener("click", function () {
var isBtnChecked = (btn.dataset.checked === "true");
if (isBtnChecked) {
unsubscribeNotification();
unsubscribe();
}
else {
subscribeNotification();
subscribe();
}
});

//To generate curl command to send push notification
function logCurlCommand(endPoint) {
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;");
function curlCommand(subscription) {
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(curlCommand);
}

//Form data with info to send to server
function dataToServer(subscription) {
var headers = new Headers();
headers.append("Content-Type", "application/json");

$.ajax({
url: "/send_notification.php?sid=" + endpoint + "&call=true"
})
.done(function(data) {
console.log(data);
});


// //Fetch api to send push notification
// fetch("" + "/send_notification.php?sid=" + endpoint, {
// headers: headers
// })
// .then(function(response) {
// return response.json();
// })
// .then(function (response) {
// console.log("push notification response -->", response);
// })
// .catch(function(error) {
// console.log(error);
// });

function sendPushNotification(subscription) {
navigator.serviceWorker.ready
.then(function(registration) {
registration.pushManager.getSubscription()
.then(function (subscription) {
curlCommand(subscription); //To log curl command in console

fetch("http://127.0.0.1:3000/send_notification", {
method: "post",
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(subscription)
})
.then(function(response) {
return response.json();
})
.then(function(data) {
console.error("data", data);
})
})
})
}

//To send push notification
var pushBtn = document.getElementById("send-push");
pushBtn.addEventListener("click", function () {
if (!endpoint) {
endpoint = JSON.parse(localStorage.getItem("endpoint"));
dataToServer(endpoint);
}
else {
dataToServer(endpoint);
}
sendPushNotification();
});
14 changes: 14 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"name": "demo",
"description": "Demo - progress web application",
"version": "0.0.1",
"dependencies": {
"body-parser": "^1.15.0",
"express": "^4.13.4",
"node-gcm": "^0.14.0"
},
"devDependencies": {},
"scripts": {
"start": "node server.js"
}
}
52 changes: 52 additions & 0 deletions server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
var express = require("express");
var bodyParser = require("body-parser");
var gcm = require('node-gcm');
var app = express();

//Here we are configuring express to use body-parser as middle-ware.
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

//To server static assests in root dir
app.use(express.static(__dirname));

//To allow cross origin request
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});

//To server index.html page
app.get("/", function (req, res) {
res.sendFile(__dirname + "/index.html");
});

//To receive push request from client
app.post("/send_notification", function (req, res) {
if (!req.body) {
res.status(400);
}

var message = new gcm.Message();
var temp = req.body.endpoint.split("/");
var regTokens = [temp[temp.length - 1]];

var sender = new gcm.Sender('AIzaSyCjrU5SqotSg2ybDLK_7rMMt9Rv0dMusvY'); //API Key

// Now the sender can be used to send messages
sender.send(message, { registrationTokens: regTokens }, function (error, response) {
if (error) {
console.error(error);
res.status(400);
}
else {
console.log(response);
res.status(200);
}
});
});

app.listen(3000, function() {
console.log("Local Server : http://localhost:3000");
});
Loading

0 comments on commit 522e66c

Please sign in to comment.