16

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 Answer 1

13

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:

https://developer.chrome.com/docs/extensions/mv2/tut_analytics/

2
  • 1
    Oh, thanks! It's working completely now and I have submitted my extension :) Oct 20, 2012 at 8:31
  • Anyone knows can I view tracking in debug mode? Or this just affect when submit to store. I do as above tutorial, but in GA nothing to see when I use debug mode.
    – Freelancer
    Oct 30, 2017 at 17:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.