将随机数添加到脚本标签

Add nonce to script tag

我想给动态构造的脚本标签添加随机数。以下不会向生成的脚本标记添加任何随机数。有人知道如何添加随机数吗?

var _wss = document.createElement('script');
_wss.nonce = 'random-string';
_wss.type = 'text/javascript';
_wss.charset = 'utf-8';
_wss.async = true;
_wss.src = "url";
var __wss = document.getElementsByTagName('script')[0];
__wss.parentNode.insertBefore(_wss, __wss);

结果是:

<script type="text/javascript" charset="utf-8" async src="url"></script>

预期结果:

<script nonce="random-string" type="text/javascript" charset="utf-8" async src="url"></script>

谢谢!

如果您想动态地 import/construct 脚本,您必须使用 strict-dynamic CSP 源而不是 nonce

The strict-dynamic source expression specifies that the trust explicitly given to a script present in the markup, by accompanying it with a nonce or a hash, shall be propagated to all the scripts loaded by that root script. At the same time, any allow-list or source expressions such as 'self' or 'unsafe-inline' are ignored.

Source MDN - CSP: script-src

您还可以在 内容安全策略 (CSP) 中阅读更多相关信息并查看一些示例 快速参考指南.

我 运行 你的代码在这个 Whosebug 页面上,它有效。

我认为您遇到的问题是您希望将随机数视为脚本标记的属性,但它仅在 javascript 中作为 属性 可用。

标签看起来像这样

<script type="text/javascript" charset="utf-8" async="" src="url"></script>

但是如果你运行

console.log(document.getElementsByTagName('script')[0].nonce)

会显示"random-string"

原因是安全。参见 https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/nonce#accessing_nonces_and_nonce_hiding。具体

For security reasons, the nonce content attribute is hidden (an empty string will be returned).

The nonce property is the only way to access nonces: