A service worker is an event-driven worker registered against an origin and a path. It takes the form of a JavaScript file that can control the web page/site it is associated with, intercepting and modifying navigation and resource requests, and caching resources in a very granular fashion to give you complete control over how your app behaves in certain situations (the most obvious one being when the network is not available.)
Source: MDN
This code that will be executed in the Document context, (or) this JavaScript will be included in your page via a <script>
tag.
// we check if the browser supports ServiceWorkers if ('serviceWorker' in navigator) { navigator .serviceWorker .register( // path to the service worker file 'sw.js' ) // the registration is async and it returns a promise .then(function (reg) { console.log('Registration Successful'); }); }
This is the service worker code and is executed in the ServiceWorker Global Scope.
self.addEventListener('fetch', function (event) { // do nothing here, just log all the network requests console.log(event.request.url); });