How To: Google Analytics In Chrome Extensions


Google Analytics

Google has replaced its legacy analytics library with the new and improved Universal Analytics library

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.


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'; object-src 'self'"

Insert the below code into your background page script.

// Standard Google Universal Analytics code
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
})(window,document,'script','','ga'); // Note: https protocol here

ga('create', 'UA-XXXXX-YY', 'auto'); // Enter your GA identifier
ga('set', 'checkProtocolTask', function(){}); // Removes failing protocol check. @see:
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.


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