Content Script tracking with Google Analytics

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


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']);
        }
    });