挂钩所有Fetch Api AJAX请求 [英] Hook all Fetch Api AJAX requests

查看:89
本文介绍了挂钩所有Fetch Api AJAX请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您如何挂钩使用Fetch Api的所有AJAX请求?以前我们可以做这样的事情来挂钩所有XMLHttpRequest:

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

或者更好的是,如果你想添加到上面的函数,你将如何挂钩所有Fetch Api和所有XMLHttpRequest AJAX请求?

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

推荐答案

实际上,本地浏览器支持获取 Api有一个界面: fetch
构造函数返回一个 Promise ,你无法获得 Request Response 当你想要返回你的Promise来重写fetch的构造函数时。

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

那么,这是否意味着我们无法挂钩所有Fetch Api? 不!

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

首先,感谢 window.fetch polyfill

然后,让我们做点什么(编辑 fetch.js )和摇滚。

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

这篇关于挂钩所有Fetch Api AJAX请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆