lzl124631x
lzl124631x

Reputation: 4809

How to use Google Analytics in Chrome Extension?

This official tutorial seems outdated because ga.js is deprecated according to this.

Besides, in the tutorial it has: _gaq.push(['_setAccount', 'UA-XXXXXXXX-X']); but UA-XXX-X is property ID not account ID.

The latest seems to be analytics.js

I tried this solution but it doesn't work for me. I saw error

Refused to load the script 'https://www.google-analytics.com/analytics.js' because it violates the following Content Security Policy directive: "script-src 'self' https://www.googletagmanager.com". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.

I'm using the following code in popup.js

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

ga("create", "UA-XXXXX-X", "auto");
ga('set', 'checkProtocolTask', null); // Disables file protocol checking.
ga('send', 'pageview', '/popup'); // Set page, avoiding rejection due to chrome-extension protocol 

And in manifest.json I have

"content_security_policy": "script-src 'self' https://www.googletagmanager.com; object-src 'self'"

  1. What's the latest right way to use Google Analytics in Chrome Extension?
  2. Which URL should I put in the "Web URL" field when creating a new property in Google Analytics?

Upvotes: 4

Views: 1263

Answers (1)

Michele Pisani
Michele Pisani

Reputation: 14197

A solution solution would be to remove the protection your CSP is supposed to offer, however you have to choose between the convenience of GTM or the security via a CSP, you can find an article about that here: https://www.simoahava.com/analytics/google-tag-manager-content-security-policy/

Upvotes: 0

Related Questions