3

I'm working on a single page application that incorporates a third party tool for analytics (think heap, segment, mixpanel, etc.). I'd like to be able to monitor the outgoing https requests from my app and perform some actions (logging for example) accordingly.

Is there a browser agnostic / procotol agnostic way of doing this? (a js library would be fine). From what I found my options are to create handlers for individual types of requests. For example, for xhr requests I could use this and for fetch requests I could use this.

Thanks.

Jay K.
  • 546
  • 2
  • 10
  • 17
  • The solutions from those two links are already browser agnostic, aren't they? They look like they might work, btw, but I'd be VERY careful with monkey patches. Here are some common pitfalls: https://en.wikipedia.org/wiki/Monkey_patch#Pitfalls – Dennis Hackethal Oct 02 '20 at 22:37

1 Answers1

1

Their are a few options, with different levels of browser support.

The simplest might be to use a Service Worker

https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API

Another option would to create a Proxy() on XMLHttpRequest, but that is not supported in IE11

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy

David Bradshaw
  • 11,859
  • 3
  • 41
  • 70
  • 1
    Got it, didn't know this was a use case for service workers! Seems like intercepting xhr requests aren't supported in service workers though? https://stackoverflow.com/questions/35879844/can-service-workers-respond-to-synchronous-xhr-requests Also, for xhr, sounds like I can use [this](https://stackoverflow.com/a/6036392/6590661) approach to get browser compatibility? Right now, my main use case is intercepting all xhr requests, so my linked solution sounds like my best bet, – Jay K. Oct 02 '20 at 23:12