Hook all Fetch Api AJAX requests

本小妞迷上赌 提交于 2019-12-22 04:16:12

问题


How would you hook all AJAX requests that use the Fetch Api? Previously we could do something like this to hook all XMLHttpRequest:

(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);
    };
  })();

Or better yet, if you wanted to add to the function above, how would you hook all Fetch Api and all XMLHttpRequest AJAX requests?


回答1:


In fact, Fetch Api is supported by native browser and only has one interface: fetch. The constructor return one Promise, and you can't get the RequestResponse when you want to return your Promise to rewrite the fetch's constructor.

The following code doesn't work well.

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

So,Does it mean we can't hook all Fetch Api ? NO!

Firstly, thanks the window.fetch polyfill.

Then, let's do something(edit fetch.js) and rock.

(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,
        // ...

Last, hook every thing as your better!

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))
    }
    // ...


来源:https://stackoverflow.com/questions/44728723/hook-all-fetch-api-ajax-requests

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