Google's Universal Analytics is out of beta, so now is a good time to update any Google Chrome extensions with the new code. Except that Google haven't updated their tutorial just yet.

Here's the steps for adding Universal Analytics to your Google Chrome extension:

Update your manifest.json

manifest.json


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

}

Update your Options page

I'm just assuming here that you want to track events in your options page. In your options page e.g. at /options.html, add a reference to the tracking javascript in a separate file:


<!DOCTYPE html>
<html>
<head>
...
<script src="js/options.js"></script>
...
</head>
<body>
...
</body>
</html>

Update your tracking code

Add the tracking JavaScript e.g. at js/options.js with the Universal Analytics code. Note the "https" at the start of the script address.


// Standard Google Universal Analytics code
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); // Note: https protocol here

ga('create', 'UA-XXXXX-YY', 'auto');
ga('set', 'checkProtocolTask', function(){}); // Removes failing protocol check. @see: http://stackoverflow.com/a/22152353/1958200
ga('require', 'displayfeatures');
ga('send', 'pageview', '/options.html');

There are 3 points I'd particularly like to highlight:

  1. Specify "https" at the start of the script address to match with the listing in the manifest.json file
  2. Override checkProtocolTask with an empty function
  3. Send a virtual pageview by specifying the path – '/options.html' – otherwise Google Analytics will reject a URL in the format
    chrome-extension://gdocgfhmbfbbbmhnhmmejncjdcbjkhfc/options.html

If that all went well, you should soon see page tracking in Google Analytics, like so:

ga-options