在 JavaScript 中检测网页上的提取 API 请求
Detect fetch API request on web page in JavaScript
背景: 我正在使用 Shopify ScriptTag,它允许我在店面添加一个 JavaScript 文件。我只有那个脚本文件。
当前行为: 有一个选项,"Buy It Now",允许客户通过跳过添加到购物车直接结账.当他们单击 立即购买 时,Shopify 会向 [=49= 发送 fetch() POST 请求] 创建结帐。
问题: 我需要在我自己的 JavaScript 文件中检测到这个 "fetch request happened"。
self.addEventListener('fetch', event => {
console.log("event happened");
});
我试过 Fetch Event API,但它似乎只能在 Service Worker 范围内工作。
有没有可能检测到这个?
就像我们可以通过使用原型继承覆盖其 open 方法来检测 XMLHttpRequest。
是的,您可以在 运行 您自己的代码之后(或之前)用您自己的调用原始 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]));
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]));
使用Performance Observer。感谢@guest271314。
背景: 我正在使用 Shopify ScriptTag,它允许我在店面添加一个 JavaScript 文件。我只有那个脚本文件。
当前行为: 有一个选项,"Buy It Now",允许客户通过跳过添加到购物车直接结账.当他们单击 立即购买 时,Shopify 会向 [=49= 发送 fetch() POST 请求] 创建结帐。
问题: 我需要在我自己的 JavaScript 文件中检测到这个 "fetch request happened"。
self.addEventListener('fetch', event => {
console.log("event happened");
});
我试过 Fetch Event API,但它似乎只能在 Service Worker 范围内工作。
有没有可能检测到这个?
就像我们可以通过使用原型继承覆盖其 open 方法来检测 XMLHttpRequest。
是的,您可以在 运行 您自己的代码之后(或之前)用您自己的调用原始 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]));
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]));
使用Performance Observer。感谢@guest271314。