What is the correct content security policy for Google Analytics?

谁说胖子不能爱 提交于 2020-02-05 05:03:29

问题


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.

来源:https://stackoverflow.com/questions/41118558/what-is-the-correct-content-security-policy-for-google-analytics

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