Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect fetch API request on web page in 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.

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.

like image 596
awebartisan Avatar asked Feb 22 '19 04:02

awebartisan


2 Answers

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.

like image 104
awebartisan Avatar answered Sep 21 '22 01:09

awebartisan


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]));
like image 36
CertainPerformance Avatar answered Sep 19 '22 01:09

CertainPerformance