PhantomJS – how to skip Google analytics code when fetching a web page

PhantomJS can be used to test websites and for automating various tasks. When testing a website in production, it may not be a good idea to execute Google analytics code. Here is quick code snippet to skip fetching Google analytics code when using PhantomJS.

var url = require('system').args[1];
var page = require('webpage').create();
page.onResourceRequested = function (requestData, request) {
  console.log('url requested: ' + requestData.url);
  if (/www.google-analytics\.com\//.test(requestData.url)) {
    console.log('Aborting request to GA ' + requestData.url);
    request.abort();
  }
};
page.open('http://dev.infoheap.com/', function (status) {
  if (status !== 'success') {
    console.log('Unable to access network');
  } else {
    console.log("Done...");
    phantom.exit(0);
  }
});

Here is the output (some part of it) from above code:

...
url requested: http://www.google-analytics.com/analytics.js
Aborting request to GA http://www.google-analytics.com/analytics.js
...

Improved version of skipping Google analytics approach

This approach may have a slight problem. This will also skip Google analytics javascript to be fetched. This may cause few javascript errors on that page. Better approach is to fetch the analytics javascript and not the metric collection code as shown below:

var url = require('system').args[1];
var page = require('webpage').create();
page.onResourceRequested = function (requestData, request) {
console.log('url requested: ' + requestData.url);
if (/www.google-analytics\.com\/r\/collect/.test(requestData.url)) {
    console.log('Aborting request to GA ' + requestData.url);
    request.abort();
  }
};
page.open(url, function (status) {
  if (status !== 'success') {
    console.log('Unable to access network');
  } else {
    console.log("Done...");
    phantom.exit(0);
  }
});

Here is the output (some part of it) from above code:

...
url requested: https://www.google-analytics.com/r/collect?v=1&_v=j40&a=1975811097&t=pageview&_s=1&dl=http%3A%2F%2Fdev.infoheap.com%2F&ul=en-us&de=UTF-8&dt=dev%20InfoHeap%20-%20Tech%20tutorials%2C%20tips%2C%20tools%20and%20more&sd=32-bit&sr=1024x768&vp=400x300&je=0&_u=QEAAAUQAK~&jid=1452159943&cid=879026602.1449483079&tid=UA-38219083-1&_r=1&z=517835023
Aborting request to GA https://www.google-analytics.com/r/collect?v=1&_v=j40&a=1975811097&t=pageview&_s=1&dl=http%3A%2F%2Fdev.infoheap.com%2F&ul=en-us&de=UTF-8&dt=dev%20InfoHeap%20-%20Tech%20tutorials%2C%20tips%2C%20tools%20and%20more&sd=32-bit&sr=1024x768&vp=400x300&je=0&_u=QEAAAUQAK~&jid=1452159943&cid=879026602.1449483079&tid=UA-38219083-1&_r=1&z=517835023
...
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments