-
Overcoming Content Security Policy (CSP) restrictions for GA4 on Chrome Extension
Hey there!
Looks like I’m in a bit of a pickle! I’ve been having a go at developing a Chrome Extension and I want to use GA4 for analytics. So, for my manifest.json (v2), I’ve written something like this:
`javascript
“background”: {
“scripts”: [“src/bg/background.js”, “src/bg/ga4.js”],
“persistent”: true
},
“content_security_policy”: “script-src ‘self’ https://www.googletagmanager.com; object-src ‘self'”
`
I’ve then tried to add the following in ga4.js:
`javascript
var script = document.createElement(‘script’); script.type = ‘text/javascript’; script.async = true;
script.src = ‘https://www.googletagmanager.com/gtag/js?id=G-*******’;
var s = document.getElementsByTagName(‘script’)[0]; s.parentNode.insertBefore(script, s);window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag(‘js’, new Date());gtag(‘config’, ‘G-******’);
`
First hitch! I’m faced with an error saying that the script ‘https://www.googletagmanager.com/gtag/js?id=G-******’ is refusing to load because it apparently violates the Content Security Policy directive.
I thought of fixing it by using a background HTML page and adding the script snippet from GA4 to the <head> tag, but no such luck! If I do that, my extension breaks.
So what’s the secret to struggling through this CSP hurdle? Has anyone run into this and found a way around it?
Log in to reply.