Skip to content

Instantly share code, notes, and snippets.

@lunaroyster
Last active February 16, 2018 18:06
Show Gist options
  • Save lunaroyster/7689806dec7ce596acc04d77f58c396f to your computer and use it in GitHub Desktop.
Save lunaroyster/7689806dec7ce596acc04d77f58c396f to your computer and use it in GitHub Desktop.
Things to remember if you're writing an extension and trying to get Google Analytics working.
  • When setting up your Analytics property, you can pick any domain. You could go with example.org, if you don't have one.
  • There are multiple variants of Google Analytics scripts. You want to pick analytics.js: https://www.google-analytics.com/analytics.js
    Pick analytics.js
  • Add the domain to your content security policy in the manifest { "content_security_policy": "script-src 'self' https://www.google-analytics.com; object-src 'self'" }
  • This code works. It's intended for a background/event page:
    window.onload = ()=>{  
        window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;   
        ga('create', 'UA-<Your ID>-<here>', 'auto');  
        ga('set', 'checkProtocolTask', null);  
        ga('send', 'pageview', '/background.js');  
    }

Here's why:

  • checkProtocolTask checks if the page is on http/https. Since extensions aren't on that protocol, you want to disable that check.

  • Whenever you send a pageview, you HAVE to send it with the current location ('/background.js'). This is important, as your request isn't originating from the domain you picked in the first step

  • When you're using analytics on an options page or a popup, you can use chrome.extension.getBackgroundPage().ga to access the Google Analytics API

function init() {
    let backgroundPage = chrome.extension.getBackgroundPage();
    backgroundPage.ga('send', 'pageview', '/optionsPage.js');
}

window.onload = init;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment