Javascript - Track any xmlhttprequest

╄→гoц情女王★ 提交于 2021-01-28 05:05:41

问题


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 XMLHttpRequests 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!