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

2022-01-20 00:00:00 fetch javascript fetch-api

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

Background: I am working with the Shopify ScriptTag which allows me to add a JavaScript file on the storefront. All I have is that script file.

当前行为:有一个选项立即购买",允许客户通过跳过添加到购物车直接结帐.当他们点击 立即购买 时,Shopify 会向 checkouts.json 发送一个 fetch() POST 请求以创建结帐.

Current Behaviour: There is an option, "Buy It Now", which allow customers to checkout directly by skipping Add To Cart. When they click on Buy It Now, Shopify sends a fetch() POST request to checkouts.json to create the checkout.

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

Problem: I need to detect that this "fetch request happened" in my own JavaScript file.

self.addEventListener('fetch', event => {
    console.log("event happened");
});

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

I have tried Fetch Event API, but it seems to be only working in Service Worker scope.

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

Is there a possibility to detect this?

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

Like we can detect XMLHttpRequest by overriding its open method using prototypal inheritance.

推荐答案

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

Yes, you can overwrite window.fetch with your own function that calls the original window.fetch after (or before) running your own code:

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('
')[0]));

相关文章