1

I'm trying to set up Google Analytics on my website. Although I'm having problems with the content security policy. I get the following console error when I load my page:

Refused to load the script 'https://www.google-analytics.com/analytics.js' because it violates the following Content Security Policy directive: "script-src 'self' 'unsafe-inline' www.google-analytics.com ajax.googleapis.com".

What is the correct way to load the 'https://www.google-analytics.com/analytics.js' script onto my website? Is there a way to fix this without removing the meta tag from the code below? Is there a content security policy that would allow the below code to work?

To replicate this problem you can just create an empty html file, copy paste the below code, and open the html file. You should see the same error in the console.

<html>
  <head>
    <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline' www.google-analytics.com ajax.googleapis.com;">
    <script>
      (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-12345678-9', 'auto');
      ga('send', 'pageview');

    </script>
  </head>
  <body>
    <h1>My website</h1>
  </body>
</html>

This question is similar although I've tried changing the above code's content policy to match what's suggested there. Although, I still get errors.

Community
  • 1
  • 1
cycloidistic
  • 305
  • 3
  • 12
  • try removing the `meta` – AMD Dec 13 '16 at 10:19
  • @AMD removing the meta works. Although this wouldn't fix my problem in my original website (which produces the same exact error). I'll update the question to ask about how this can be solved without removing the meta tag. – cycloidistic Dec 13 '16 at 10:24
  • 1
    Possible duplicate of [Google Analytics and Content-Security-Policy header](http://stackoverflow.com/questions/14592598/google-analytics-and-content-security-policy-header) – Ivan Solntsev Dec 13 '16 at 10:29
  • @IvanSolntsev AMD answered the question when I didn't have the not removing meta restriction. I just recently edited it to add that restriction based off AMD's comment. – cycloidistic Dec 13 '16 at 10:30
  • @IvanSolntsev just edited to show how I think it's not a duplicate. – cycloidistic Dec 13 '16 at 10:39
  • you might try asking on http://webmasters.stackexchange.com/ as well – Linda Lawton - DaImTo Dec 13 '16 at 11:12

0 Answers0