Is there a way for a ServiceWorker
(or other mechanism) to detect when resources are being downloaded?
For example, I'd like to be notified if any of the following happen:
<img src>
downloadsbackground-image: url(...)
downloads@import
and is fetching resources<script src>
downloadsXMLHTTPRequest
or fetch
Short of hacking open the XMLHttpRequest.prototype
methods, does JavaScript offer a way to listen to network activity?
It's sort of the opposite to this question about idle network activity
Yes, the Service Worker catches all fetch events you listed. Register a service worker with:
navigator.serviceWorker.register('/service-worker.js');
In your service worker script, install a handler for the fetch
event:
// `self` is a ServiceWorkerGlobalScope
self.addEventListener('fetch', function(event) {
console.log("fetch event:", event.request.url);
});
Here's a plunker that demonstrates this. You'll need to run the demo twice from the Live Preview (once to register the service worker, and again to see the fetch events in the console). Don't forget to unregister the service worker from DevTools as cleanup: DevTools > Resources/Applications > Service Workers (left panel) > Delete (right).
Yes, that's kind of the whole point of ServiceWorker.
Limitation of ServiceWorker (according to spec): you won't be able to intercept requests for <object
> or <embed>
resources, nor navigation requests. Both restrictions are designed as security measures.
I suggest you begin reading at the Handle Fetch section of ServiceWorker spec.
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