0

It's not easy to get Google Analytics/Google Ads working with CSP. I checked out a number of SO articles including this one, but wanted to see if there was another approach.

I found a pretty easy way to do it in this article, and wanted to post it here in case it may be useful to others. I'll post it here as an answer.

VikR
  • 4,818
  • 8
  • 51
  • 96

1 Answers1

0

I found a pretty easy way to do it in this article:

...move the Google Analytics code snippet to an external code file, hosted on a domain that is already allowlisted by your script-src directed, such as the primary domain of your website.

The script originally supplied by Google was:

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

    gtag('config', 'UA-##########');
</script>

I went to https://www.googletagmanager.com/gtag/js?id=UA-##########, downloaded the script, and added this to the bottom of it:

window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());

gtag('config', 'UA-##########');

I saved it to my website. I added this:

<script async src="/script-saved-to-my-website.js"></script>

...inside the head section. (Google ads seems to want it inside the head section for some reason).

I added csp policy as described in the above article.

I connected Google Analytics 4 to Google Ads using the "connect to Google ads" feature I found in Google Analytics. Note: you have to have Google Ads in Expert mode, not Smart mode, for this to work.

I set up a Conversion goal on Google Ads.

And... it's working. :) I can see my stats on Google Analytics and my conversions on Google Ads.

VikR
  • 4,818
  • 8
  • 51
  • 96