【问题标题】:Add nonce to script tag将随机数添加到脚本标记
【发布时间】:2021-07-11 08:26:18
【问题描述】:

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

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>

谢谢!

【问题讨论】:

  • 请分享更多详细信息 - 当您运行该代码时会发生什么?预期的结果是什么?
  • 感谢您的评论。编辑了问题。

标签: javascript nonce


【解决方案1】:

如果您想动态导入/构建脚本,则必须使用 strict-dynamic CSP 源而不是 nonce

strict-dynamic 源表达式指定显式给予标记中存在的脚本的信任,通过伴随它的随机数或散列,应传播到所有脚本由该根脚本加载。同时,任何允许列表或源表达式(例如“self”或“unsafe-inline”)都会被忽略。

来源MDN - CSP: script-src

您还可以在Content Security Policy (CSP) Quick Reference Guide 上阅读有关它的更多信息并查看一些示例。

【讨论】:

    【解决方案2】:

    我在这个 stackoverflow 页面上运行了你的代码,它工作正常。

    我认为您遇到的问题是您希望将 nonce 视为脚本标记的属性,但它仅在 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。具体

    出于安全原因,nonce 内容属性是隐藏的(一个空的 字符串将被返回)。

    nonce 属性是访问 nonce 的唯一方法:

    【讨论】:

      猜你喜欢
      • 2016-02-26
      • 2015-10-01
      • 1970-01-01
      • 2010-12-27
      • 1970-01-01
      • 2015-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多