XHR interceptor: add request ID to event details

Sometimes an interceptor exists for both the request and response bodies
of a request, and we need to pair request with response. In order to
allow this, this change adds a request ID in the event details so the
two events can be linked together.

Change-Id: I1360a38dc6362925ccc8609f77ee3d871874902a
diff --git a/src/common/xhrInterceptorUtils.js b/src/common/xhrInterceptorUtils.js
index baa2bd3..867c323 100644
--- a/src/common/xhrInterceptorUtils.js
+++ b/src/common/xhrInterceptorUtils.js
@@ -31,10 +31,11 @@
   return undefined;
 }
 
-export function triggerEvent(eventName, body) {
+export function triggerEvent(eventName, body, id) {
   var evt = new CustomEvent('TWPT_' + eventName, {
     detail: {
       body,
+      id,
     }
   });
   window.dispatchEvent(evt);
diff --git a/src/injections/xhrInterceptor.js b/src/injections/xhrInterceptor.js
index 8630ca3..3ea4474 100644
--- a/src/injections/xhrInterceptor.js
+++ b/src/injections/xhrInterceptor.js
@@ -3,8 +3,11 @@
 const originalOpen = XMLHttpRequest.prototype.open;
 const originalSend = XMLHttpRequest.prototype.send;
 
+let messageID = 0;
+
 XMLHttpRequest.prototype.open = function() {
   this.$TWPTRequestURL = arguments[1] || location.href;
+  this.$TWPTID = messageID++;
 
   let interceptors = utils.matchInterceptors('response', this.$TWPTRequestURL);
   if (interceptors.length > 0) {
@@ -12,7 +15,7 @@
       var body = utils.getResponseJSON(this);
       if (body !== undefined)
         interceptors.forEach(i => {
-          utils.triggerEvent(i.eventName, body);
+          utils.triggerEvent(i.eventName, body, this.$TWPTID);
         });
     });
   }
@@ -40,7 +43,7 @@
     var JSONBody = JSON.parse(body);
 
     interceptors.forEach(i => {
-      utils.triggerEvent(i.eventName, JSONBody);
+      utils.triggerEvent(i.eventName, JSONBody, this.$TWPTID);
     });
   }
 };