- 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
- 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;