How To: Google Analytics In Chrome Extensions

Background

Google Analytics

Google has replaced its legacy analytics library https://ssl.google-analytics.com/ga.js with the new and improved Universal Analytics library https://www.google-analytics.com/analytics.js.

I’ve been working on a Google Chrome Browser Extension but had some trouble integrating it with Google Analytics. Google’s own tutorial hadn’t yet been updated to use the new analytics library. In this post I’ll explain how I did it.

My app was architected in such as a way that the content script would send messages to the background script which would in turn record key events using the Google Analytics library. While looking for a solution I came this fantastic tutorial by David Simpson.

Solution

First, update your manifest.json file to allow the analytics.js library to be fetched from google. Without this your extension will be unable to fetch the library due to the default security policy applied by Chrome.

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

Insert the below code into your background page script.

// 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'); // Enter your GA identifier
ga('set', 'checkProtocolTask', function(){}); // Removes failing protocol check. @see: http://stackoverflow.com/a/22152353/1958200
ga('require', 'displayfeatures');
ga('send', 'pageview', '/mypage.html'); // Specify the virtual path

It’s worth noting that there are a few changes have been made to the default script.

  • The analytics.js lib is fetched over HTTPS because Chrome’s default Content Security Policy prevents resources being fetched over HTTP.
  • Resources for Chrome Extensions are loaded using address chrome-extension:///<extension id>/<resource>. This is not compatible with Google Analytics, the library can only be loaded using protocol HTTP or HTTPS. The protocol check has therefore been disabled.

Following this, I could see successful requests being made in my extension’s background page.

Screenshot

Shane Bartholomeusz

G’day, I’m a technical solutions consultant based in Perth, Australia that specialises in the Microsoft technology stack, including .NET, Dynamics 365, Azure and general web development etc.

This blog is my place to share my thoughts, helpful solutions and just random nerdy stuff.
Shane Bartholomeusz

Latest posts by Shane Bartholomeusz (see all)

One thought on “How To: Google Analytics In Chrome Extensions

Leave a Reply