Problem in underscore.js with "new Function()" when CSP header is set
From html5rocks, set the nonce in the Content-Security-Policy header:
Content-Security-Policy: script-src 'nonce-EDNnf03nceIOfn39fn3e9h3sdfa'
Place the nonce somewhere on your page:
...
<body data-nonce="EDNnf03nceIOfn39fn3e9h3sdfa">
...
Call the function below with the nonce value in question before you start using underscore in your scripts.
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'));
Hope there is a better way than this.