在 JavaScript 中检测网页上的 fetch API 请求

awe*_*san 5 javascript fetch fetch-api

背景:我正在使用 Shopify ScriptTag,它允许我在店面添加 JavaScript 文件。我只有那个脚本文件。

当前行为:有一个选项“立即购买”,允许客户跳过Add To Cart直接结账。当他们点击一口,Shopify发送取() POST请求checkouts.json创建结账。

问题:我需要在我自己的 JavaScript 文件中检测这个“获取请求发生”。

self.addEventListener('fetch', event => {
    console.log("event happened");
});
Run Code Online (Sandbox Code Playgroud)

我试过Fetch Event API,但它似乎只在Service Worker范围内工作。

有没有可能检测到这一点?

就像我们可以通过使用原型继承覆盖其open方法来检测XMLHttpRequest一样。

awe*_*san 7

const observer = new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    if (entry.initiatorType === "fetch") {
      console.log('Fetch request detected to', entry.name);
    }
  }
});

observer.observe({
  entryTypes: ["resource"]
});

fetch('https://cors-anywhere.herokuapp.com/')
  .then(res => res.text())
  .then(text => console.log(text.split('\n')[0]));
Run Code Online (Sandbox Code Playgroud)

使用性能观察器。感谢@guest271314。

  • 这个答案应该优于当前接受的覆盖“window.fetch”的答案。 (2认同)

Cer*_*nce 5

是的,您可以window.fetch使用自己的函数覆盖window.fetch在运行您自己的代码之后(或之前)调用原始代码:

const nativeFetch = window.fetch;
window.fetch = function(...args) {
  console.log('detected fetch call');
  return nativeFetch.apply(window, args);
}

fetch('https://cors-anywhere.herokuapp.com/')
  .then(res => res.text())
  .then(text => console.log(text.split('\n')[0]));
Run Code Online (Sandbox Code Playgroud)