Tomorrow I will be visiting the HackConf at Sofia, Bulgaria. Thus, today I was part of a workshop for Progressive Web Applications and I will try to summarize how to build an application, which simply displays something like the Facebook messenger below:
First it asks politely, whether it is allowed to give notifications and then it gives these upon an event:
So, let’s start from the very beginning – what do you need to run something as simple as this?
- Node.js
- Npm and the command npm install in the console
- Then a simple button with an id in an index.html file
- A server worker file, looking like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
addEventListener('install', event => { event.waitUntil((async () => {})()); }); addEventListener('activate', event => { event.waitUntil((async () => { console.log("Step 2"); await clients.claim(); let swClients = await clients.matchAll(); swClients.forEach(function(el) { console.log(el); }); })()); }); |
- A main.js file, looking like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
document.addEventListener('DOMContentLoaded', () => { if ('serviceWorker' in navigator) { console.warn ("Activating step 1") navigator.serviceWorker.register('/sw.js').then(function(registration) { console.warn('Service worker registration succeeded:', registration); }).catch(function(error) { console.warn('Service worker registration failed:', error); }); } else { console.warn('Service workers are not supported.'); } }); function reply_click(clicked_id) { console.log(clicked_id); Notification.requestPermission().then(function(result) { if (result === 'denied') { console.log('Permission wasn\'t granted. Allow a retry.'); return; } if (result === 'default') { console.log('The permission request was dismissed.'); return; } var link = document.getElementById(clicked_id); link.style.visibility = 'hidden'; useNotificationApi(); }); } function useNotificationApi(){ navigator.serviceWorker.getRegistration().then(function(reg){ var options = { body: "Here is notification body", icon: "conf.png", }; reg.showNotification("Hello world", options); }); }; |
- The whole application is present here GitHub Repo
Cheers! 🙂