问题
Can I check any XmlHttpRequest, executable on page without adding addEventListener each of it? I try add
document.addEventListener("loadend"...)
but nothing happend. Looks like requests don't have a global events?
// EDITED //
I need detect new elements, which loaded by ajax. Great solution for it- here
Using MutationObserver
回答1:
I think you should rethink your design. Why do you want to do this. Are there better options?
However if you really want to do this you could "hack" it by overwriting the standard XmlHttpRequest
object with your own. You will have to do this before any XmlHttpRequest
is initiated though to make it work for all objects.
//store the original XMLHttpRequest in a variabele so you can use it yourself
var originalXMLHttpRequest = XMLHttpRequest;
//Overwrite the original object with your own in which you create an instance of the original object, add an event listner to it and return that.
XMLHttpRequest = function() {
var req = new originalXMLHttpRequest();
req.addEventListener("loadend", function() {
console.log("loadend event fired");
});
return req;
};
//Test if it works
httpReq = new XMLHttpRequest();
httpReq.open("GET", "https://stackoverflow.com/");
httpReq.send();
回答2:
Make your XMLHttpRequest
s fire a custom event when they're done and then listen for those events.
var r = new XMLHttpRequest();
r.onload = function() {
e = new CustomEvent('myLoadend', {detail: {foo: 'bar'}});
document.dispatchEvent(e);
}
And listen to those events:
document.addEventListener("myLoadend"...)
来源:https://stackoverflow.com/questions/55041883/javascript-track-any-xmlhttprequest