Skip to content Skip to sidebar Skip to footer

Google Analytics.js And Content Security Policy

I have a web app using the default html5boilerplate Content Security Policy. However, we have the new Google analytics.js snippet on the page, which is being blocked by the CSP. I'

Solution 1:

You seem to have CSP headers setup on your web app, where Google Analytics domains are not white-listed yet. All the requests that the client makes to external domains should be explicitly white-listed. (This is a good reference: https://hacks.mozilla.org/2016/02/implementing-content-security-policy/).

The CSP errors you see on the browser console are quite descriptive about what has to be white-listed in your CSP header.

For example, for this case,

Refused to load the image 'https://www.google.co.in/...' because it violates the following Content Security Policy directive: "img-src ".

this would solve the error:

img-src https://www.google.co.in <other-domains> 

Solution 2:

Using the alternate way described on https://developers.google.com/analytics/devguides/collection/analyticsjs/ helped. It is much like OP described in the second edit, you can either use a custom inline script that you apply a nonce on or outsource the inline script content into a seperate script, like OP suggested. Don't forget the async attribute on the script tag that references analytics.js.

Using this method, there will be no errors/warnings as no scripts are injected to your html.

Here is the relevant part from the link I posted:

Alternative async tracking snippet

While the JavaScript tracking snippet described above ensures the script will be loaded and executed asynchronously on all browsers, it has the disadvantage of not allowing modern browsers to preload the script.

The alternative async tracking snippet below adds support for preloading, which will provide a small performance boost on modern browsers, but can degrade to synchronous loading and execution on IE 9 and older mobile browsers that do not recognize the async script attribute. Only use this tracking snippet if your visitors primarily use modern browsers to access your site.

<!-- Google Analytics -->
<script>
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
ga('create', 'UA-XXXXX-Y', 'auto');
ga('send', 'pageview');
</script>
<script async src='https://www.google-analytics.com/analytics.js'></script>
<!-- End Google Analytics -->

Solution 3:

your .htaccess solution should be all correct.

why should you brake the (clientside) asynchronous nature of it ?

in the browser console you will see which requests to which hosts are blocked, if there are any blocked request from gugl while surfing the page you can add the hostname to your policy-setting


Post a Comment for "Google Analytics.js And Content Security Policy"