Google Analytics tracking in Chrome Extension's background.html

帅比萌擦擦* 提交于 2019-12-03 18:30:29

问题


When I realized that I cannot track directly in content script. I start to work with background HTML tracking my data. via Content Script tracking with Google Analytics

When I set up my background script, I figured out that it doesn't support inline script. So I put the code in a js file and use "src=filename.js" to include that. via chrome extension insert content script on browser action

But finally there is a trouble: I cannot load ga.js at all because it still violates the rule. Here is what I got:

Refused to load the script 'https://ssl.google-analytics.com/ga.js' because it violates the following Content Security Policy directive: "script-src 'self' chrome-extension-resource:".

My extension structure:

  1. background.html
  2. script.js
  3. tracker.js

More information about this issue:

background.html:

<html>
<script src="tracker.js"></script>
<body></body>
</html>

tracker.js: (I hide my ID)

var _gaq = _gaq || [];
_gaq.push(['_setAccount', _gaID]);
_gaq.push(['_trackPageview']);

(function() {
  var ga = document.createElement('script');
  ga.type = 'text/javascript';
  ga.async = true;
  ga.src = 'https://ssl.google-analytics.com/ga.js';
  var s = document.getElementsByTagName('script')[0];
  s.parentNode.insertBefore(ga, s);
})();

Thanks for any kind of help!


回答1:


It looks good. You are on the right track. You just need to update your manifest.json file to allow scripts to be downloaded from the google domain.

Assuming you are using manifest.json file with manifest_version:2. You should add this line to the manifest

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

More info:

http://developer.chrome.com/extensions/tut_analytics.html



来源:https://stackoverflow.com/questions/12985723/google-analytics-tracking-in-chrome-extensions-background-html

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