How to know when AJAX request was initiated within webpage?


#1

I've a webpage which consists Javascript files of other domains as I use third party tools, what I want to do is whenever an javascript function initiates an AJAX request

how can I access it's information like the URL, request type etc... using another thread of Javascript?


#2

Push the F12 key in your browser to see the developer tools.
The Network tab contains a list of all requests made by the webpage.


#3

No, I know that, but I want to access that information using Javascript, I've edited the question please check again.


#4

You may be able to write a browser extension that could do what you want.


#5

You might monkey patch the native XMLHttpRequest to log, for example, the arguments passed to .open() like so:

// Keep a reference to the original `.open()` method
var open = XMLHttpRequest.prototype.open

// Add your own logic
XMLHttpRequest.prototype.open = function () {
  console.log(arguments)
  // Apply the original method
  open.apply(this, arguments)
}

// Some 3rd party code opens an XHR...
var xhr = new XMLHttpRequest()

xhr.open('GET', 'data.json') // will log ['GET', 'data.json']
xhr.send()

This will, however, not work if that XHR is getting opened in a different thread (such as from a web worker) -- it modifies the XMLHttpRequest.prototype for the current thread only.