Skip to content

Instantly share code, notes, and snippets.

@moshfeu
Created September 1, 2019 05:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moshfeu/350494cbc8a849131a5db4983563bd11 to your computer and use it in GitHub Desktop.
Save moshfeu/350494cbc8a849131a5db4983563bd11 to your computer and use it in GitHub Desktop.
Polling data from the server and show notification if there a new data
<button onclick="sendMessage('start')">Start Listen</button>
<button onclick="sendMessage('stop')">Stop Listen</button>
<script>
let se;
navigator.serviceWorker.register('/sw.js').then(data => {
se = data.active;
console.log('se ready!');
});
function sendMessage(message) {
if (!se) {
console.log('sw is not ready yet');
return;
}
se.postMessage(message);
}
Notification.requestPermission().then(registration => {
console.log(registration);
});
</script>
// content of index.js
const http = require('http')
const port = 3000
const requestHandler = (request, response) => {
response.writeHead(200, {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
});
response.end(JSON.stringify(new Array(3).fill(0).map((u, i) => ({
_id: i
}))));
}
const server = http.createServer(requestHandler)
server.listen(port, (err) => {
if (err) {
return console.log('something bad happened', err)
}
console.log(`server is listening on ${port}`)
})
let interval;
let cache = [];
self.addEventListener('notificationclick', function(event) {
event.notification.close();
event.waitUntil(clients.matchAll({
type: 'window'
}).then(function(clientList) {
if (clientList.length) {
const [client] = clientList;
if ('focus' in client) {
return client.focus();
} else if (clients.openWindow) {
return clients.openWindow('/#notification');
}
}
}));
});
function startListen() {
interval = setInterval(() => {
fetch('http://localhost:3000')
.then(data => data.json())
.then(data => {
if (data.some(i => !cache.includes(i._id))) {
sendNotification();
cache = data.map(u => u._id);
}
});
}, 1000);
}
function stopListen() {
clearInterval(interval);
}
function sendNotification() {
self.registration.showNotification(`New user!`, {
body: 'Click to go to approval panel',
icon: '',
tag: '',
});
}
self.addEventListener('message', ({data}) => {
switch (data) {
case 'start':
startListen();
break;
case 'stop':
stopListen();
break;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment