Jquery 与它无关。 a.innerHTML = u[1] + S.htmlPrefilter(o) + u[2] 构造用于调用 .html() / .append() / .prepend() 方法将 HTML 代码插入 DOM。
由于这会导致 CSP 违规,这意味着您插入的 HTML 代码包含内联样式:<tag style='...' 或 <style>...</style>。您有 2 个选择:
- 重构 JS 代码以摆脱这种内联样式插入。
- 使用this hack 将
style= 或<style>...</style> 替换为与CSP 兼容的等效项。
hack 的想法是覆盖 htmlPrefilter() 方法,默认情况下它是 empty,旨在根据您的需要重新定义。
如果 style= 导致 CSP 违规,您可以使用类似:
$.htmlPrefilter = function( html ) {
// Really it have to be more complicated for replacing a tag's attributes only,
// not just plain text replacement:
return ( html + '' ).replace( / style=/gi, ' data-style=' );
};
那么当使用.html()/.append()/.prepend()方法时,所有style=inline_styles_here属性将被data-style='inline_styles_here'替换。
为了 CSP 安全,将真正的 CSS 样式应用于您可以使用这样的脚本的标签:
$(function() { // On page loads
var tags = document.querySelectorAll('[data-style]');
for (var tag of tags) {
var attr = tag.getAttribute('data-style')
var arr = attr.split(';').map( (el, index) => el.trim() );
for (var i=0, tmp; i < arr.length; ++i) {
if (! /:/.test(arr[i]) ) continue; // Empty or wrong style
tmp = arr[i].split(':').map( (el, index) => el.trim() );
tag.style[ camelize(tmp[0]) ] = tmp[1];
}
}
function camelize(str) {
return str
.split('-')
.map( (word, index) => index == 0 ? word : word[0].toUpperCase() + word.slice(1) )
.join('');
}
)}
Javascript 不是我的强项,重写上面的脚本以使用原生 jquery 调用。
如果 <style>...</style> 导致 CSP 违规,您可以重新定义 htmlPrefilter() 以将 <style> 替换为 <style nonce='value'>,但您必须以某种方式将“nonce”传递给脚本。