How to run a function when any XMLHttpRequest completes?

I am working on a project that has several scenarios that I cannot change. These scripts refresh the page through AJAX. When the update is complete, I need to run some code.

Is there any event that fires when any XMLHttpRequest completes? (or XMLHttpRequest state change?).

Unfortunately, I cannot access the specific XMLHttpRequest object used to execute the request.

Thanks,

+6
source share
1 answer

Without jQuery, you can connect the open method to attach a listener for each XHR readystatechange at the time the XHR object is open ed. Make sure the following code works before Ajax happens:

 // save the real open var oldOpen = XMLHttpRequest.prototype.open; function onStateChange(event) { // fires on every readystatechange ever // use `this` to determine which XHR object fired the change event } XMLHttpRequest.prototype.open = function() { // when an XHR object is opened, add a listener for its readystatechange events this.addEventListener("readystatechange", onStateChange) // run the real `open` oldOpen.apply(this, arguments); } 

Alternatively, if you only care about successful load events, you can listen to this event instead of readystatechange .

+15
source

Source: https://habr.com/ru/post/951826/


All Articles