在页面上的所有AJAX请求中添加一个“hook”

在页面上的所有AJAX请求中添加一个“hook”,第1张

在页面上的所有AJAX请求中添加一个“hook”

我不确定 脚本中的注释 是否有用 ,当然 仅适用于使用本机XMLHttpRequest对象的浏览器
我认为如果正在使用javascript库,它将起作用,因为如果可能的话,它们将使用本机对象。

function addXMLRequestCallback(callback){    var oldSend, i;    if( XMLHttpRequest.callbacks ) {        // we've already overridden send() so just add the callback        XMLHttpRequest.callbacks.push( callback );    } else {        // create a callback queue        XMLHttpRequest.callbacks = [callback];        // store the native send()        oldSend = XMLHttpRequest.prototype.send;        // override the native send()        XMLHttpRequest.prototype.send = function(){ // process the callback queue // the xhr instance is passed into each callback but seems pretty useless // you can't tell what its destination is or call abort() without an error // so only really good for logging that a request has happened // I could be wrong, I hope so... // EDIT: I suppose you could override the onreadystatechange handler though for( i = 0; i < XMLHttpRequest.callbacks.length; i++ ) {     XMLHttpRequest.callbacks[i]( this ); } // call the native send() oldSend.apply(this, arguments);        }    }}// e.g.addXMLRequestCallback( function( xhr ) {    console.log( xhr.responseText ); // (an empty string)});addXMLRequestCallback( function( xhr ) {    console.dir( xhr ); // have a look if there is anything useful here});


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5602089.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-15
下一篇2022-12-15

发表评论

登录后才能评论

评论列表(0条)

    保存