Javascript 在php中启用内容安全性时,如何执行从jQueryAjax请求检索的内联脚本

Javascript 在php中启用内容安全性时,如何执行从jQueryAjax请求检索的内联脚本,javascript,php,jquery,ajax,Javascript,Php,Jquery,Ajax,我正在从事一个项目,其中启用了一个内容安全策略,该策略只允许执行带有nonce的内联脚本 header("Content-Security-Policy: script-src 'nonce-".$nonce."';"); 因此,在页面“我的脚本”标记中插入了nonce,如下所示: <script nonce="<?php echo $nonce; ?>" src="/static/js/global.js

我正在从事一个项目,其中启用了一个内容安全策略,该策略只允许执行带有nonce的内联脚本

header("Content-Security-Policy: script-src 'nonce-".$nonce."';");
因此,在页面“我的脚本”标记中插入了nonce,如下所示:

<script nonce="<?php echo $nonce; ?>" src="/static/js/global.js"></script>

我找到了将来遇到这个问题的其他人的原因。这与脚本标记的工作方式以及JQuery如何附加它们有关。使用.append()或.html()函数时,JQuery将从追加脚本标记开始,但在追加之后,浏览器将立即检查新的脚本标记是否存在nonce。由于JQuery在附加脚本标记之前没有将nonce添加为属性,因此浏览器现在会禁用该新脚本标记,因为它在创建时缺少nonce。解决方法是使用我自己的函数来附加脚本,如下所示:

//create a script tag node
let node = document.createElement("script"); 

//this is the element where the script will get appended
let vr = document.getElementById("change-region"); 

//insert your nonce here from wherever you retrieve it from
let nonce = "sd234r8hf8wresiu"; //insert your nonce here from wherever you get your nonce

//add the nonce to the new script node we made
node.setAttribute("nonce", nonce); 

//add the source of your script
node.setAttribute("src", "/source/of/script");

//append the node of the script element and it should be accepted by the browser this time
vr.appendChild(node);
可能使用
eval()
//create a script tag node
let node = document.createElement("script"); 

//this is the element where the script will get appended
let vr = document.getElementById("change-region"); 

//insert your nonce here from wherever you retrieve it from
let nonce = "sd234r8hf8wresiu"; //insert your nonce here from wherever you get your nonce

//add the nonce to the new script node we made
node.setAttribute("nonce", nonce); 

//add the source of your script
node.setAttribute("src", "/source/of/script");

//append the node of the script element and it should be accepted by the browser this time
vr.appendChild(node);