15
votes

I am working on a Google Chrome Extension that modifies certain pages with a content script. In order to understand when and where those changes are applied we were looking into google analytics since we use it for other web properties already.

We include the ga.js library via the manifest file, and trigger _trackPageview with a synchronous page call when we apply a change to a page.

var pageTracker = _gat._getTracker("UA-our-UA");    
pageTracker._setDomainName("none");
pageTracker._setAllowLinker(true);    
pageTracker._trackPageview(window.location.href);

Trouble here is that each pageView in a different domain counts as a new visit and visitor. Its there a way to circumvent that? For example it use a chrome extension sqlite database or key value store in the browser to store unique user id and visit id domain independent. Is this possible?

Thanks

2

2 Answers

27
votes

You should not execute that code inside other people sites. The Google Analytics configuration is somewhat sensitive and if a site has a custom implementation you might be breaking it for that visitor.

You should include Google Analytics in your own background page. And then communicate from the content_script back to your background page everytime you need to track an event.

By including the GA script on your background script is nice because you don't interfere with other code on the website and it always execute from the same domain and thus will use the same cookies not causing duplicated visits/visitors.

Here are more info on how to install GA on your background page.

https://developer.chrome.com/docs/extensions/mv2/tut_analytics/

And here's the docs for passing information from Content Scripts to your background page:

http://code.google.com/chrome/extensions/messaging.html

14
votes

As Eduardo said in his answer you need a background page, so that can be done like that:

in your manifest.json file:

,
"content_security_policy": "script-src 'self' https://ssl.google-analytics.com; object-src 'self'"
,

in content_scripts.js whenever you want to track event, send a message to the background page to trigger that event.

chrome.runtime.sendMessage({action: "yourEvent"});

background.js

    (function() {
      var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
      ga.src = 'https://ssl.google-analytics.com/ga.js';
      var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();

    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-XXXXXXX-X']);

    // here we receive the coming message from the content script page
    chrome.runtime.onMessage.addListener(function( request, sender, sendResponse ) {
        if(request.action == "yourEvent"){
            _gaq.push(['_trackEvent', "eventCategory", 'eventType']);
        }
    });