“inline-style”-Error with Content Security Policy and Javascript

孤人 提交于 2019-12-08 17:01:25

Updated:

Because you are converting from a DOMElement to text(via innerHTML) any elements with modified styles get converted into inline styles. I've included an example to illustrate this.

var el = document.getElementById('sample'), 
output = document.getElementById('output'),
affect = document.getElementById('affected');

affect.style.backgroundColor = "#369";
affect.style.color = "#FFF";

output.innerText+=el.innerHTML;
#sample {
  margin:10px;
}

#output {
  margin: 10px;
}
<div id="sample">
  <div id="affected">
  Sample DIV
  </div>
</div>
<div id="output">
  Output: 
</div>

Therefore when you set the innerHTML of the copy, you are including the styles that had modified the element as inline styles which violates your policy.

You could technically make a duplicate copy of the DOM element instead, and insert it to the DOM tree directly. For that, take a look at the MDN Documentation for Cloning Nodes. My old answer is still valid in the case the DOM manipulation is not viable.

Old Answer:

According to the MDN documentation on CSP you can solve it by sending the following header:

style-src 'unsafe-inline' 'self'; default-src 'self';

Here is the documentation for default-src.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!