OnClick 违反内容安全政策

OnClick violating Content Security Policy

我有一个附加到 HTML/EJS 页面的外部脚本。该脚本使用 'createElement' 和 'setAttribute' 命令将图像填充到页面。此外,我创建了一个 'onclick' 属性,以便在其中一个创建的图像是 'clicked' 时 运行 一个函数。外部'.js'文件的代码类似如下:

addEventListener("load", initialize);

const vitals = document.querySelector('#passed');

const _convert = vitals.dataset.pix.split(",");  
  //convert the passed ('dataset') string into an array...

function initialize() {

...

  //**ADD THE PHOTO...

  _item = document.createElement("img"); 
  _item.setAttribute("id", "pix_" + _str);
  _item.setAttribute("src", "/gallery/photo/" + _convert[_count]);
  _item.setAttribute("onclick", "reRouter(this);");  
  _item.setAttribute("alt", "picture of " + _str);
  _item.setAttribute("width", '100%');
  document.getElementById("group_" + _tally).appendChild(_item);

...

}

function reRouter(_sent) {

//do stuff based upon the 'clicked' image...
//the Content Security Policy error is thrown ONLY upon a click of an image created in the 'initialize' function above...WHY?

}

'initialize' 函数似乎 运行 正确,页面根据需要填充了指定文件夹中的图像。但是,当我对其中一张图像执行 'mouse click' 时,我发现违反了内容安全策略,如下所示:

“拒绝执行内联事件处理程序,因为它违反了以下内容安全策略指令:“script-src-attr 'none'”。'unsafe-inline' 关键字、散列('sha256-...'),或者需要随机数 ('nonce-...') 才能启用内联执行。"

为什么点击鼠标会抛出这样的错误?奇怪的是 'initialize' 函数 运行 很好,并且不会抛出错误...它只发生在图像上的鼠标 'click' 上。非常感谢任何建议。

您的外部脚本可能来自您在 CSP 中列出的来源。 onclick 代码实际上是内联 javascript,除非您指定 'unsafe-inline',否则它会被阻止。即使 Chrome 建议使用散列,它也不会将其作为事件处理程序接受为 onclick。在 CSP 级别 3(尚未得到广泛支持)中,您可以使用 'unsafe-hashes' 进行这项工作:https://content-security-policy.com/script-src/

解决方案是在您的外部脚本中添加一个事件侦听器来处理 onclick 事件。