GTM not propagating nonce to Custom HTML tags

隐身守侯 提交于 2020-12-15 05:45:07

问题


In order to implement Content-Security-Policy, I need to pass nonce to GTM to allow tags. Using nonce-aware version of GTM snippet works great for all tag types except Custom HTML.

Is there a way to pass nonce to Custom HTML and allow custom scripts, without using unsafe-inline?


回答1:


In order to add the nonce attribute to the Custom HTML scripts, it must be first defined as a GTM variable:

  1. Add id="gtmScript" to the nonce-aware version of GTM snippet - this will be used to target the element and capture nonce.
<script id="gtmScript" nonce="{GENERATED_NONCE}">
  // GTM function
</script>
  1. In GTM, create a new variable that will capture the nonce. Use DOM Element type, and select the ID of the GTM snippet.


Now that the nonce variable is available in the GTM, add it to the Custom HTML script.

<script nonce="{{nonce}}">
  console.log("CSP-allowed script with nonce:", "{{nonce}}");
</script>

If the tag is not firing, check the Support document.write. This can be a key step in Single Page Applications. The GTM Custom HTML script is now nonce-allowed and fires as expected. Of course, any assets used by this script will now need to be allowed in the CSP header.


Script within a script

Many tracking scripts are creating and firing additional script within themselves. These will also be blocked as inline-scripts. Find out where and how they are created, and add nonce to them as well.

Usually, the code looks similar to this:

var script = document.createElement("script");
script.type = "text/javascript";
script.async = true;
script.src = "https://tracking.js";
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(script, s);

Edit this part of the code and insert the nonce variable, in the same manner along with other attributes.

script.nonce = "{{nonce}}";

Again, pay attention and whitelist any necessary assets that are now being blocked from this newly allowed script.

That's it - Custom HTML script is now fully CSP-allowed.


Source and disclaimer: I'm the author of expanded dev.to guide



来源:https://stackoverflow.com/questions/65100704/gtm-not-propagating-nonce-to-custom-html-tags

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!