In this post I ll try to answer, what is service worker and how can we use it?
What is Service Worker?
How we can use Service Worker?
Service worker can intercept network requests, can modify requests and also can originate new requests to server using fetch API. That means it is a great tool for providing cache.
Service worker can be used for background-sync and displaying push messages as well as pre-fetching images/css/js assets from server.
Service worker can be installed, removed and updated. That is just like we install, reinstall or uninstall some software from our system.
Where can I see Service Worker?
You can use browser web/dev tools to see how service worker is loaded.
Service worker can not access DOM because it is a separate thread.
Service worker is fully asynchonous (non blocking), that means localStorage and synchronous XHR can not be used.
Service worker can receive push messages from server and display them in browser notifications even the web app is not opened in the browser.
Service Worker run only over HTTPS because they can intercept network calls and can modify them.
How we communicate with the web page?
We can use the postMessage method i.e navigator.serviceWorker.controller.postMessage(data) to send some data from the web app to service worker and in service worker to accept that data we can add message event listener like self.addEventListner(‘message’
How to share data between Service-Worker and a Web page?
Hence Service-worker are async the sync storage like localStorage can not be used to share data, we can use IndexedDB to share data between Service-Worker and web app.