1

I am trying to get Google Analytics events to fire from a chrome browser extension. I have the following code in my content script to inject ga:

(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://ssl.google-analytics.com/analytics.js','ga');

ga('create', 'UA-XXXXXXXX-Y', 'auto', 'myTracker');

ga('myTracker.send', 'event', 'test_category', 'test_action', 'test_label');

In my manifest.json, I added the following line:

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

The event does not seem to be triggering as it does not show up in my Google Analytics console. Does anybody know where I could be going wrong?

Thanks very much.

vdutz
  • 31
  • 3
  • Put that code in a [sandboxed page](https://developer.chrome.com/extensions/sandbox) inside iframe in your background page. – wOxxOm May 08 '18 at 20:17
  • Thanks very much for the suggestion. However, I think sending the GA event from the background page would mean losing information in my case. – vdutz May 10 '18 at 14:49

1 Answers1

0

Add these two lines after 'create' command:

// will disable checks for http(s) protocol
ga('set', 'checkProtocolTask', function(){}); 

// set your page here, helps to avoid rejection because of chrome-extension protocol
ga('send', 'pageview', '/popup.html'); 

You can find more in this discussion: How do you integrate Universal Analytics in to Chrome Extensions?

Denis L
  • 3,209
  • 1
  • 25
  • 37