在 JavaScript 中检测网页上的 fetch API 请求 [英] Detect fetch API request on web page in JavaScript

查看:31
本文介绍了在 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]));

这篇关于在 JavaScript 中检测网页上的 fetch API 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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