2017-06-23 8 views
3

Fetch Apiを使用するすべてのAJAXリクエストをどのようにフックしますか?以前は、我々はすべてのXMLHttpRequestフックする、このような何かを行うことができます:あなたは上記の機能に追加したい場合は、より良いまだHook all Fetch Api AJAXリクエスト

(function() { 
    var origOpen = XMLHttpRequest.prototype.open; 
    XMLHttpRequest.prototype.open = function() { 
     console.log('request started!'); 
     this.addEventListener('load', function() { 
      console.log('request completed!'); 
      console.log(this.readyState); //will always be 4 (ajax is completed successfully) 
      console.log(this.responseText); //whatever the response was 
     }); 
     origOpen.apply(this, arguments); 
    }; 
    })(); 

かを、どのようにすべてのAPIと、すべてのXMLHttpRequest AJAX要求を取得するフックのでしょうか?

+0

これで運がいいですか?仕様には何もないようです。 – Seth

答えて

0

実際には、フェッチ Apiはネイティブブラウザでのみサポートされており、1つのインターフェイス:fetchを持っています。 コンストラクタはPromiseを返します。プロミスを返してフェッチのコンストラクタを書き換える場合は、Request,Responseを取得できません。

次のコードはうまく機能しません。

(function() { 
    var oldFectch = fetch; 
    fetch.consotructor = function() { 
     return new Promise(resolve, reject) { 
      // your hook code 
     }; 
    }; 
})(); 

だから、Fetch Apiをすべてフックできないのでしょうか? NO!

まずは、window.fetch polyfillに感謝します。

次に、何か(編集fetch.js)とロックをしましょう。

(function(self) { 
    'use strict'; 

    // comment or delete the following code block 
    // if (self.fetch) { 
    // return 
    // } 

    var support = { 
     searchParams: 'URLSearchParams' in self, 
     iterable: 'Symbol' in self && 'iterator' in Symbol, 
     // ... 

最後に、すべてのものをあなたの方に引き付けよう!

self.fetch = function(input, init) { 
    return new Promise(function(resolve, reject) { 
    var request = new Request(input, init) 
    var xhr = new XMLHttpRequest() 

    // Here we go! 
    // Now we get the XMLHttpRequest Object 
    // Do what you want! 

    xhr.onload = function() { 
     var options = { 
     status: xhr.status, 
     statusText: xhr.statusText, 
     headers: parseHeaders(xhr.getAllResponseHeaders() || '') 
     } 
     options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL') 
     var body = 'response' in xhr ? xhr.response : xhr.responseText 
     resolve(new Response(body, options)) 
    } 
    // ...