Reputation: 1870
I'm reading the ServiceWorker getting started docs https://developers.google.com/web/fundamentals/getting-started/primers/service-workers.
So first we register our ServiceWorker with the scope. So I did that as below
<!DOCTYPE html>
<html>
<head>
<title>Getting started with Service Worker</title>
</head>
<body>
<script type="text/javascript">
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('/sw.js').then(function(registration) {
// Registration was successful
console.log('ServiceWorker registration successful with scope: ', registration.scope);
}, function(err) {
// registration failed :(
console.log('ServiceWorker registration failed: ', err);
});
});
}
</script>
</body>
</html>
and created a sw.js file and wrote a console.log inside sw.js
console.log("This is sw.js")
So when I access the index.html file the first time, that console.log is executed and ServiceWorker registration successful message is printed. But when I refresh the page second time, it only prints the message ServiceWorker registration successful. So why didn't it executed the console.log inside sw.js for the second time. I was expecting it to execute that console.log second time. Am I missing the point here?
Upvotes: 4
Views: 4636
Reputation: 1636
Service workers are scripts that are basically executed once (in background) when they are registered. If you need to execute some recurrent code, you need to use service worker API:
A service worker is an event-driven worker registered against an origin and a path.
The install event is called asynchronously after you call navigator.serviceWorker.register('/sw.js')
; that's why it returns a Promise, to which you pass a callback
function (the one with the content console.log('ServiceWorker registration successful ...');
).
Upvotes: 4
Reputation:
A service worker is designed to sit in between your website and the network. So while you load your page initially, it runs the script once and installs the service worker if you have added an event to listen for installs.
Once that's done, you need to attach a listener to the 'fetch' event to capture all your requests inside your page. So basically if you want to console.log every time a request is made, you can do the following:
self.addEventListener('fetch', event => {
console.log(event);
})
Upvotes: 1