Is there a way to simulate network conditions from JavaScript?

Viewed 210

In the developer tools of Firefox, one can choose to simulate conditions like certain types of mobile data connections. Is there a way to activate this from JavaScript, without requiring users to open up the developer console?

1 Answers

Depending on your use case, you could either

  1. Install a service worker that listens to the “fetch” event, then calls event.respondWith with a delay (HTTPS required);
  2. Intercept a call to fetch / XMLHttpRequest in the application scope to do the same thing (overwrite window.fetch and/or window.XMLHttpRequest) - note this won’t affect images / resources loaded directly from HTML;
  3. Set a HTTP cookie or header and make your server / delay before responding (lots of users doing this may reduce server concurrency however)

Note that if you want to emulate this kind of behaviour with a streamed resource (e.g. progressive JPEGs, HTML), your best bet is the service worker route, where you can construct a ReadableStream directly (see here for some inspiration: https://developers.google.com/web/updates/2016/06/sw-readablestreams).

For the actual streaming behaviour itself I would consider using something like an RxJs pipeline, which would make it easy for you to introduce delays, arbitrary stops etc. to simulate different network conditions.

Related