1. ホーム
  2. javascript

[解決済み] ページ上のすべてのAJAXリクエストに "フック "を追加する

2022-08-12 16:45:06

質問

すべての AJAX リクエスト (送信されようとしているとき、またはイベント時) にフックしてアクションを実行することが可能かどうかを知りたいのです。この時点では、ページ上に他のサードパーティのスクリプトがあると仮定しています。これらの中には、jQueryを使用しているものもあれば、そうでないものもあるかもしれません。これは可能ですか?

どのように解決するのですか?

インスピレーション avivの答え に触発されて、少し調べてみたところ、このようなことがわかりました。

そんなに便利なものなのかなぁ スクリプトのコメント通り、そしてもちろん はネイティブの 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
});