Google analytics intercept all requests
Google is actually using gif to sync the data to its server, so intercepting the XHR requests wont work.
In analytics.js there is an official way to do that. via Tasks, here is some small untested example:
ga(function(tracker) {
var originalSendHitTask = tracker.get('sendHitTask');
tracker.set('sendHitTask', function(model) {
var payLoad = model.get('hitPayload');
originalSendHitTask(model);
var gifRequest = new XMLHttpRequest();
var gifPath = "http://localhost/collect";
gifRequest.open('get', gifPath + '?' + payLoad, true);
gifRequest.send();
});
});
make sure that the pageView is sent after this code is executed.
I would demonstrate how you can intercept any AJAX call. Taking from this generic solution, you can filter the GA requests and take the actions you want.
I modified this answer.
The idea behind this solution is modifying the open
and send
prototype methods of XMLHttpRequest
object and do the interception there. The IIFE gets the XMLHttpRequest
object, saves the original prototype methods, install new methods and call the original methods from within the new methods. And, of course, do what you want with the data in the mean time.
(function(XHR) {
//Save the original methods
var open = XHR.prototype.open;
var send = XHR.prototype.send;
//Hook new open method in order to get the url
XHR.prototype.open = function(method, url, async, user, pass) {
this._url = url;
//Call the original
open.call(this, method, url, async, user, pass);
};
//Hook here too. This will be executed just before the data is sent
XHR.prototype.send = function(data) {
if (this_url === GA_URL_CONST) //Symbolic const
SendDataToMyServer(data); //Symbolic Fn
//Call the original
send.call(this, data);
}
})(XMLHttpRequest);