Migrate from analytics.js to gtag.js with CSP

453 Views Asked by At

I have a website with analytics.js and and a content security policy (CSP). I'd like to add a Google ads remarketing audience.

The documentation is quite confusing because it seems that gtag.js that is used with Google analytics is similar but different to Google Tag Manager (GTM).

This is my current analytics snippet:

(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-XXX-1', 'auto');
ga('set', 'dimension1', 'value');
ga('set', 'userId', 'X');
ga('send', 'pageview');

Google has instructions for using GTM with a CSP here. Though the URL for GTM is different from the url provided by analytics for using gtag.js. sigh

Anyway, after combing through a bunch of docs, I arrived at this:

(function(w,d,s,l,i){
  w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;var n=d.querySelector('[nonce]');n&&j.setAttribute('nonce',n.nonce||n.getAttribute('nonce'));f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','UA-XXX-1');
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config',
     'UA-XXX-1',
     {'user_id': uuid,
      'custom_map': {'dimension1': 'user_status'}});
gtag('event', 'user_status_event', {'user_status': user_status});

but the Google analytics audience data is still blank.

Any ideas for how to get this working?

1

There are 1 best solutions below

0
On

I've switched to this because it is less complicated:

  <script nonce='{{ nonce }}' async src="https://www.googletagmanager.com/gtag/js?id=UA-XXX-1"></script>
  <script nonce='{{ nonce }}'>
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());
    gtag('config',
         'UA-XXX-1',
         {'custom_map': {'dimension1': 'user_status'}});
    gtag('event', 'user_status_event', {'user_status': user_status});
  </script>

I'll update if it works.