问题
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:
- Add
id="gtmScript"
to the nonce-aware version of GTM snippet - this will be used to target the element and capturenonce
.
<script id="gtmScript" nonce="{GENERATED_NONCE}">
// GTM function
</script>
- 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