1

I am working on a site, which uses a 3rd party library to launch a pop up to collect users email addresses.

After the user submits the email address, the 3rd party API is called, following the format https://<API-URL>/collectemail?email=test%40test.com

I want to run a function when that API is called and pass it the email param. How can I listen for that event and then trigger my function?

1
  • 2
    How does the library make the request? jQuery? XHR/fetch? Sep 17, 2020 at 19:16

1 Answer 1

0

The best way would be to fork the library and modify it so that, when the API is called, the library code itself calls the code on your site with the email parameter.

If that's not possible, your only other option is to monkeypatch XMLHttpRequest so as to intercept requests, such as with:

// Your code, make sure this runs first:
const origXHR = window.XMLHttpRequest;
window.XMLHttpRequest = function() {
  const xhr = new origXHR();
  xhr.open = (method, url) => {
    origXHR.prototype.open.call(xhr, method, url);
    console.log('Connection just opened to:', url);
  }
  return xhr;
};


// Library code:
const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://example.com/?email=test%40test.com');
xhr.send();

3
  • Thank you very much for this. Unfortunately, the 3rd party code is proprietary and only supplied in the minified version, so I can't fork & edit. I have tried to implement your second solution, however, in Google Chrome dev tools, the API call is being listed as "script", and this code isn't catching the call, so I think it may actually be making the call with JQuery? Sep 17, 2020 at 21:19
  • If it's actually using jQuery, then you will be able to patch into it by adding an ajaxStart or ajaxComplete handler. $(document).on('ajaxComplete', (event, xhr, options) => { console.log(options); }); Sep 18, 2020 at 1:15
  • This code won't have anything to do with caching - if the response is cached, it'll be cached regardless of whether the XHR has been patched like this or not. Sep 18, 2020 at 1:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.