Question

Creating events on APIs response

  • 1 November 2023
  • 1 reply
  • 10 views

How to create event that track the success response of the APIs?
The user performed an action say clicked a button, which is associated to an API call, then how can I track whether the response of the API was success or failure?


1 reply

Userlevel 5
Badge

Hey@himanshu_v_verma! Thanks for reaching out! 😊

One option you could try is setting up an event listener on your page to send network requests that errored in as a custom event. You could try adding the below code immediately at the end of your FullStory snippet, but before the closing </script> tag (I would not recommend setting this up to track every single successful call, as there could potentially be a lot of custom events that would be especially noisy in your sessions):  

(function () {        var a = XMLHttpRequest.prototype.open;        XMLHttpRequest.prototype.open = function () {          this.addEventListener(            "readystatechange",            function () {              if (this.readyState === XMLHttpRequest.DONE) {                var a = window[window._fs_namespace];                if (!a) return console.warn("FullStory not found");                var d = this.status;                0 === d ||                  (200 >= d && 500 >= d) ||                  ((d = {                    status_int: this.status,                    statusText_str: this.statusText,                    responseURL_str: this.responseURL,                  }),                  a.event("AJAX call", d));              }            },            !1          );          a.apply(this, arguments);        };      })();      window.addEventListener("request", function (a) {        null !== window[window._fs_namespace]          ? FS.event("AJAX call", { message: a.message, filename: a.filename })          : console.warn(              "Attempted to send " +                eventName +                " to FullStory but no FS equivalent found on page"            );      });

 

I’d also like to mention that network errors (anything in the 4xx-5xx range) are already captured as an event in FS and indexed for search, so the example code above would/could lead to a duplicate (see screenshot) depending on what status code range you configured. 

Please let me know if you have any other questions as I’d be happy to help! 

Reply