Timo Cengiz
Timo Cengiz

Reputation: 3417

Refused to execute inline script because it violates the following CSP, Chrome extension

We are trying to implement google analytics in our chrome extension. These are the steps we made:

Our manifest.json was edited to this:

"Content-Security-Policy": "default-src 'self'; script-src 'nonce-4AEemGb0xJptoIGFP3Nd'",

And our index.html:

<head>

  <meta charset="utf-8">
  <script>
    window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
    ga('create', 'XXXXX', 'auto');
    ga('send', 'pageview');
</script>
<script async src='https://www.google-analytics.com/analytics.js' nonce="4AEemGb0xJptoIGFP3Nd"></script>

<!-- End Google Analytics -->
</head>

We tried using hash,nonce and unsafe inline but all gave this error code:

enter image description here

I am out of ideas.

Upvotes: 0

Views: 1469

Answers (1)

Ouroborus
Ouroborus

Reputation: 16894

Google provides a tutorial on adding GA to Chrome extensions:

Installing the tracking code

The standard Google Analytics tracking code snippet fetches a file named ga.js from an SSL protected URL if the current page was loaded using the https:// protocol. Chrome extensions and applications may only use the SSL-protected version of ga.js. Loading ga.js over insecure HTTP is disallowed by Chrome's default Content Security Policy. This, plus the fact that Chrome extensions are hosted under the chrome-extension:// schema, requires a slight modification to the usual tracking snippet to pull ga.js directly from https://ssl.google-analytics.com/ga.js instead of the default location.

Below is a modified snippet for the asynchronous tracking API (the modified line is bolded):

(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);
})();

You'll also need to ensure that your extension has access to load the resource by relaxing the default content security policy. The policy definition in your manifest.json might look like:

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

Here is a popup page (popup.html) which loads the asynchronous tracking code via an external JavaScript file (popup.js) and tracks a single page view:

<!DOCTYPE html>
<html>
  <head>
    ...
    <script src="popup.js"></script>
  </head>
  <body>
    ...
  </body>
</html>
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXXXX-X']);
_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);
})();

Upvotes: 2

Related Questions