Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can JavaScript or ServiceWorkers detect network activity / Ajax events?

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> downloads
  • a resource in a background-image: url(...) downloads
  • A stylesheet has encountered an @import and is fetching resources
  • <script src> downloads
  • Some script invokes a new XMLHTTPRequest 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

like image 707
Bryce Avatar asked Jun 09 '16 06:06

Bryce


2 Answers

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).

like image 188
tony19 Avatar answered Oct 19 '22 03:10

tony19


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.

like image 40
searlea Avatar answered Oct 19 '22 04:10

searlea