Can JavaScript or ServiceWorkers detect network activity / Ajax events? Can JavaScript or ServiceWorkers detect network activity / Ajax events? ajax ajax

Can JavaScript or ServiceWorkers detect network activity / Ajax events?


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