Reputation: 97
I'm trying to add GA4 analytics to a website, which previously had UA analytics. I've added the new GA4 code snipper beneath the <head>
tag as instructed.
The following errors (and a few others with a similar message) are appearing in the console, and I'm not sure what I'm doing wrong:
Refused to load the script 'https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXX' because it violates the following Content Security Policy directive: "default-src 'self' 'unsafe-eval' 'unsafe-hashes' 'unsafe-inline' data: blob:". Note that 'script-src-elem' was not explicitly set, so 'default-src' is used as a fallback.
analytics.js:34 [Report Only] Refused to connect to 'https://www.google-analytics.com/j/collect?XXXXX' because it violates the following Content Security Policy directive: "default-src 'self' 'unsafe-eval' 'unsafe-hashes' 'unsafe-inline' data: blob:". Note that 'connect-src' was not explicitly set, so 'default-src' is used as a fallback.
Any help or pointers in the right direction are massively appreciated!
Upvotes: 2
Views: 7303
Reputation: 652
Okay, I feel your pain. I've been through this a lot lately. However the message you are receiving is a lot more helpful than it looks at first glance.
First you need to know where your Content Security Policy is coming from, so fire up postman and poke your website and look at the headers that come back. I believe any Content Security Policy header will override anything you set in the page.
Now carefully read the content security policy and compare it to the error message, and exactly what is says is wrong ... that's what's wrong.
So referring to your specific error, if you think about it carefully you could add this to the content security policy:
script-src-elem 'unsafe-inline' www.googletagmanager.com;
Next you need to determine how to change that header. This can be tricky. The web server may need reconfiguring. Or if you're using Cloudfront, then you need to change the Response Headers in the distribution, or whatever is appropriate for the server or CDN you are using, research required.
Then, when you fix that error ... you'll be treated to a new error, for example:
Refused to connect to https://region1.google-analytics.com/g/collectPolicy
directive: default-src self unsafe-eval unsafe-inline fonts.googleapis.com.
Note that connect-src was not explicitly set, so default-src is used as
a fallback.
And you'll solve this again by fixing exactly what the message says is wrong, wash, rinse, repeat until your developer console is happy.
So in my case, to fix this issue I added (prepended) this to my existing content security policy:
connect-src *.google-analytics.com; script-src-elem 'unsafe-inline' www.googletagmanager.com;
Upvotes: 3