skip to Main Content

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.

2

Answers


  1. Chosen as BEST ANSWER

    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.


  2. 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]));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search