从html5rocks中,在 Content-Security-Policy 标头中设置随机数:
Content-Security-Policy: script-src 'nonce-EDNnf03nceIOfn39fn3e9h3sdfa'
将 nonce 放在页面上的某个位置:
...
<body data-nonce="EDNnf03nceIOfn39fn3e9h3sdfa">
...
在开始在脚本中使用下划线之前,使用相关的 nonce 值调用下面的函数。
function handleFnNonceRequirement(nonce) {
window.Function = function () {
var renderNode = document.createElement("script"),
len = arguments.length,
source = arguments[len-1],
args = [];
if ( 1 < len ) {
for ( var i=0; i<(len-1); i++ ) {
args.push(arguments[i]);
}
}
renderNode.text = "function __ifYouAbsolutelyMustUseIt() { return function("+args.join(", ")+") {" + source + "}}";
renderNode.setAttribute('nonce', nonce);
document.head.appendChild(renderNode).parentNode.removeChild(renderNode);
return __ifYouAbsolutelyMustUseIt();
};
}
handleFnNonceRequirement(document.getElementsByTagName("BODY")[0].getAttribute('data-nonce'));
希望有比这更好的方法。