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.
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.
Problem: I need to detect that this "fetch request happened" in my own JavaScript file.
self.addEventListener('fetch', event => {
console.log("event happened");
});
I have tried Fetch Event API, but it seems to be only working in Service Worker scope.
Is there a possibility to detect this?
Like we can detect XMLHttpRequest by overriding its open method using prototypal inheritance.
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]));
Using Performance Observer. Thanks to @guest271314.
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('\n')[0]));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With