GTM不会将随机数传播到自定义HTML代码 [英] GTM not propagating nonce to Custom HTML tags

查看:105
本文介绍了GTM不会将随机数传播到自定义HTML代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了实施内容安全策略,我需要将 nonce 传递给GTM以允许标签.除了自定义HTML 之外,使用 nonce-aware 版本的GTM代码片段非常适合所有代码类型.

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.

是否可以在不使用 unsafe-inline 的情况下将 nonce 传递给自定义HTML 并允许自定义脚本?

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

推荐答案

要向自定义HTML脚本添加 nonce 属性,必须首先将其定义为GTM变量:

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

  1. id =" gtmScript" 添加到GTM片段的nonce-aware版本-这将用于定位元素并捕获 nonce .
  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. 在GTM中,创建一个将捕获随机数的新变量.使用 DOM元素类型,然后选择GTM代码段的ID.
  1. In GTM, create a new variable that will capture the nonce. Use DOM Element type, and select the ID of the GTM snippet.

现在 nonce 变量在GTM中可用,将其添加到自定义HTML"脚本中.

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>

如果未触发代码,请检查支持文档.写.这可能是单页应用程序"中的关键步骤.现在允许使用GTM自定义HTML脚本,并且可以按预期触发.当然,现在需要在CSP标头中允许使用此脚本使用的所有资产.

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.

许多跟踪脚本正在内部创建并触发其他脚本.这些也将作为内联脚本被阻止.找出它们的创建位置和创建方式,并在其中添加 nonce .

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);

编辑这部分代码,并以相同的方式以及其他属性插入 nonce 变量.

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.

就这样-自定义HTML脚本现已完全支持CSP.

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

来源和免责声明:我是扩展了开发指南以

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

这篇关于GTM不会将随机数传播到自定义HTML代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆