Shane Bartholomeusz

Geek and lover of all things tech related

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


  1. Kartik Watwani

    20th June 2019 at 3:44 pm

    Thank you so much

  2. Courtney Landau

    9th January 2020 at 3:54 am

    Thank you!

  3. Saurabh Mishra

    25th June 2020 at 6:51 pm

    Refused to load the script ‘’ because it violates the following Content Security Policy directive: “script-src ‘self’“. Note that ‘script-src-elem’ was not explicitly set, so ‘script-src’ is used as a fallback.
    It gives me this error.Any clue why??

  4. Saurabh – change ssl to www in your Content Security Policy

Leave a Reply

© 2023 Shane Bartholomeusz

Theme by Anders NorenUp ↑