How to use Google Analytics in Chrome Extension?

六月ゝ 毕业季﹏ 提交于 2021-01-28 05:46:11

问题


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?

回答1:


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/



来源:https://stackoverflow.com/questions/63668590/how-to-use-google-analytics-in-chrome-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!