Google Analytics tracking code giving CORS error

2019-04-23 23:55发布

问题:

I'm using (what looks to me like) new Google Analytics tracking code that I got from my account yesterday. It makes use of some "Global site tag". I've placed it at the top of my , as GA instructs, but I'm getting a cross origin error when loading my page, so GA isn't tracking my site correctly.

This is the exact message:

Access to Script at 'https://www.googletagmanager.com/gtag/js?id={my-id}' from origin '{my website}' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value 'http://www.googletagmanager.com' that is not equal to the supplied origin.

The script that is causing this error is included like this

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="//www.googletagmanager.com/gtag/js?id={my-id}"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', '{my-id}');
</script>

That code above is exactly as it comes from Google Analytics, so I'm not sure why it isn't working..

Is anyone able to help?

回答1:

As far as this error message:

Access to Script at 'googletagmanager.com/gtag/js?id={my-id}' from origin '{my website}' has been blocked by CORS policy

…the only case when you should be seeing that error message is if your script element has a crossorigin attribute; e.g., crossorigin="anonymous".

If you’re not adding that crossorigin="anonymous" attribute in any of your own code, you may be using some CDN system that’s injecting it.



回答2:

I've run into a similar error myself. If you are new to Google Tag Manager maybe it's because you haven't published the tag manager yet. You can check if this is your case by visiting:

https://tagmanager.google.com

And checking whether the green pane says "Container Not Published"

If this is is your case, then the GTM will not load since it's kind of in "draft" mode and not ready to use.

As soon as you have published your first version, it will start working normally.

If you make any changes to your GTM, remember to publish a new version to see the results in your website.