在Chrome扩展程序上阅读响应正文的解决方法

D. *_*lsh 8 google-chrome-extension

显然,Chrome扩展程序的API不允许扩展程序读取响应正文.

https://bugs.chromium.org/p/chromium/issues/detail?id=487422

我的扩展需要读取响应主体以从页面获取数据.

我试过了...

  chrome.webRequest.onCompleted.addListener((details) => {
       fetch(details.url)
       .then(res => res.json())
       .then(res => responseFunction(res))
       .catch(err => console.log(err))
    }, { urls: ["*://*.url.com/*"], types: ["xmlhttprequest"] }
  );
Run Code Online (Sandbox Code Playgroud)

但是,这当然是一个无限循环.

我在不同的机器上设置了一个代理服务器,但这看起来很傻,效率很低.

还有其他人解决过这个问题吗?

Mic*_*rin 0

只需在请求中使用一些附加标头作为您不需要在创建的请求上执行侦听器的标志:

chrome.webRequest.onCompleted.addListener((details) => {
  if (!details.requestHeaders.find(({ name }) => name === 'some_flag')) {
    fetch(details.url, {
      headers: {
        some_flag: true,
      }
    })
      .then(res => res.json())
      .then(res => responseFunction(res))
      .catch(err => console.log(err))
  }
}, { urls: ["*://*.url.com/*"], types: ["xmlhttprequest"] });
Run Code Online (Sandbox Code Playgroud)