I'm trying to build a basic service worker to handle all AJAX requests sent from my website.
Service worker is subscribed to the fetch event. I can handle all request sent but it doesn't work the first time the service worker is installed.
Once the service worker is installed, if I refresh the web page, then the fetch event handler works.
I want my service worker to fetch all requests from the very beginning. Is it possible?
Here's the code I have:
index.html
<!DOCTYPE html>
<html>
<body>
<h2>Service Worker Demo Page</h2>
<script type="text/javascript">
if (navigator.serviceWorker) {
navigator.serviceWorker.register('./sw.js')
.then(function (registration) {
console.debug('Registration within scope %s. More details %O', registration.scope, registration);
return fetch('https://www.google.com');
})
.then(console.info)
.catch(console.warn);
}
</script>
</body>
sw.js
self.addEventListener('fetch', function (e) {
console.info('%s request to %s. More details: %o'
, e.request.method
, e.request.url
, e
);
});
The default behaviour of is that a webpage must be refreshed before its service worker becomes active. So, the "very beginning" for you (the user) is not the same "very beginning" of the service worker.
However, you can override this default behaviour by using clients.claim(). Read about it on MDN:
// sw.js
self.addEventListener('activate', function(event) {
event.waitUntil(self.clients.claim());
});
Note that for your use case you should ensure that the SW is registered and activated before firing any fetch events.
______
Read more about the service worker lifecycle in the "Service Worker Lifecycle" blog post. Here are some relevant bullet points...
- A service worker won't receive events like fetch and push until it successfully finishes installing and becomes "active".
- By default, a page's fetches won't go through a service worker unless the page request itself went through a service worker. So you'll need to refresh the page to see the effects of the service worker. clients.claim() can override this default, and take control of non-controlled pages.
Yes, it is possible.
In order to catch the very beginning requests, Service Worker must take controls over the initial pages that call those requests right after it is being activated. And unfortunately, this is not enabled by default. You still have to call clients.claim for achieving this expected behaviour.
self.onactivate = function(event){
event.waitUntil(self.clients.claim());
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With