3

Is it possible to intercept HTTP requests in browser with JavaScript which aren't done through XMLHttpRequest object (ajax)?

I'm mocking an API server with ember-cli-mirage, which is using pretender. I need to add file upload (images) to the app. Mocking upload is no issue since it's done by ajax. But I'm unable to intercept the GET request caused by image tag (non-ajax request) since pretender is only intercepting requests done through XMLHttpRequest and therefore can't return "uploaded" data.

Is there anyway I could also intercept non-ajax requests?

If not: What should be considered best practice then? This is what I've considered so far:

  1. Retrieving images through ajax so I could easily intercept the request. E.g. I could treat them as ember-data models having base64 encoded image data as an attribute. But I'm not sure about the trade-off. I'm afraid that this will cause performance issues and possible memory-leaks cause of image size (> 1MB).
  2. Passthrough requests for images and handling them in express server coming with ember-cli. But then mocking file upload would only work if app is served by ember-cli. And not being able to deploy development builds would be a big trade-off.
jelhan
  • 6,149
  • 1
  • 19
  • 35
  • Correct me if I'm wrong, but isn't Ajax's HTTP requests asynchronous; as in, the request is fired and the execution carries on regardless? As in, once it's sent, it's sent. – Joshua Jan 20 '17 at 14:17
  • @Crowes ajax requests could be mocked by overwriting `XMLHttpRequest` object. E.g. pretender.js is using this approach. But that's not the question here. – jelhan Jan 20 '17 at 14:47

1 Answers1

0

I think the only way to do this is to use a service worker.

The service workers fetch event can intercept any kind of request. However browser support is not very well yet.

Lux
  • 17,835
  • 5
  • 43
  • 73
  • I'm wondering if [Cache api](https://developer.mozilla.org/en-US/docs/Web/API/Cache) supports this use case. It's also available in window scope and provides methods like `cache.put()`. I played a little bit around but didn't succeeded. Do you know if cache api might do the trick? – jelhan Jan 23 '17 at 12:07