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

Detect fetch API request on web page in JavaScript(在 JavaScript 中检测网页上的 fetch API 请求)
本文介绍了在 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 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)