Can JavaScript or ServiceWorkers detect Ajax network activity / events?

Is there a way for ServiceWorker (or another mechanism) to detect when resources are loading?

For example, I would like to be notified if one of the following events occurs:

  • <img src> downloads
  • resource in background-image: url(...) downloads
  • Style sheet met @import and retrieves resources
  • <script src> downloads
  • Some script calls a new XMLHTTPRequest or fetch

With the exception of hacking XMLHttpRequest.prototype methods , does JavaScript offer a way to listen for network activity?

This is similar to this question about idle network activity.

+6
source share
2 answers

Yes, the service worker catches all the events you have selected. Register a service worker using:

 navigator.serviceWorker.register('/service-worker.js'); 

In the working script service, set the 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 will need to run the demo twice from the Live Preview (once to register a service worker and see the selection events in the console again). Do not forget to unregister a service worker from DevTools as a cleanup: DevTools> Resources / Applications> Service Workers (left panel)> Delete (right) .

+7
source

Yes, this is the point of ServiceWorker.

ServiceWorker restriction (as per specification): you will not be able to intercept requests for <object > or <embed> resources, as well as navigation requests. Both restrictions are designed as security measures.

I suggest you start reading in the Handle Fetch section of the ServiceWorker specification.

+3
source

All Articles