Add simple push notification demo. Fixes #42

This commit is contained in:
Marco Castelluccio 2015-11-04 13:30:39 +00:00
Родитель 759d933d74
Коммит ec4270b0e3
5 изменённых файлов: 72 добавлений и 1 удалений

Просмотреть файл

@ -40,6 +40,7 @@
"gulp-load-plugins": "^0.10.0", "gulp-load-plugins": "^0.10.0",
"gulp-swig": "^0.7.4", "gulp-swig": "^0.7.4",
"request": "^2.64.0", "request": "^2.64.0",
"swig": "^1.4.2" "swig": "^1.4.2",
"web-push": "0.0.11"
} }
} }

22
push-simple/index.html Normal file
Просмотреть файл

@ -0,0 +1,22 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Simple Push Notification - ServiceWorker Cookbook</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
font-family: monospace;
font-size: 1rem;
white-space: pre-wrap;
}
</style>
</head>
<body>
<p>This demo shows how to register for push notifications and how to send them.</p>
<button id="doIt">Try to conquer Italy!</button>
<script src="./index.js"></script>
</body>
</html>

27
push-simple/index.js Normal file
Просмотреть файл

@ -0,0 +1,27 @@
navigator.serviceWorker.register('service-worker.js').then(function(registration) {
return registration.pushManager.getSubscription().then(function(subscription) {
if (!subscription) {
return registration.pushManager.subscribe({ userVisibleOnly: true }).then(function(subscription) {
return subscription;
});
} else {
return subscription;
}
});
}).then(function(subscription) {
fetch('./register', {
method: 'post',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify({
endpoint: subscription.endpoint,
}),
});
});
document.getElementById('doIt').onclick = function() {
fetch('./sendNotification', {
method: 'post',
});
}

15
push-simple/server.js Normal file
Просмотреть файл

@ -0,0 +1,15 @@
var path = require('path');
var request = require('request');
var webPush = require('web-push');
var endpoint;
module.exports = function(app, route) {
app.post(route + 'register', function(req, res) {
endpoint = req.body.endpoint;
});
app.post(route + 'sendNotification', function() {
webPush.sendNotification(endpoint);
});
};

Просмотреть файл

@ -0,0 +1,6 @@
self.addEventListener('push', function(event) {
event.waitUntil(self.registration.showNotification('ServiceWorker Cookbook', {
body: 'Alea iacta est',
tag: 'push',
}));
});