GTM nonce-aware script does not work on all browsers for Custom HTML tags GTM nonce-aware script does not work on all browsers for Custom HTML tags google-chrome google-chrome

GTM nonce-aware script does not work on all browsers for Custom HTML tags


After searching a lot on the internet and reading different articles, I found out the solution mentioned here works perfectly well in Safari but not in other browsers because:

Chrome, Safari, and Edge mask the nonce attribute value so GTM is unable to grab it and store it as a variable.

Considering this solution for propagating the nonce to the custom HTML tags, we go ahead and apply the following changes to fix this issue on Chrome, Firefox, and Edge.As suggested here in the comments we need to modify the nonce-aware script a little bit and put the nonce in a data- attribute (then the browsers won't mask it), and push it to the dataLayer:

<!-- Google Tag Manager --><script  nonce='{{YOUR_GTM_NONCE}}'  data-gtm-nonce='{{YOUR_GTM_NONCE}}'>  (function(w,d,s,l,i){    const gtmNonce = d.querySelector('[data-gtm-nonce]').dataset.gtmNonce;    w[l]=w[l]||[];    w[l].push({'nonce': gtmNonce});    w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});    const 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;    j.setAttribute('nonce', gtmNonce);    f.parentNode.insertBefore(j,f);  })(window,document,'script','dataLayer','YOUR_GTM_ID');</script><!-- End Google Tag Manager -->

Then in the GTM, you need to change the nonce variable you defined based on this solution from this:enter image description here

to this:enter image description here

The rest will be kept the same.