Skip to content

Instantly share code, notes, and snippets.

@matthewbauer
Created August 17, 2015 16:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthewbauer/928f6a81bbfae3e86aca to your computer and use it in GitHub Desktop.
Save matthewbauer/928f6a81bbfae3e86aca to your computer and use it in GitHub Desktop.
function testNonce(nonce) {
window.okay = false;
var script = document.createElement('script');
script.text = 'window.okay = true';
document.appendChild(script);
document.removeChild(script);
return window.okay;
}
function findNonce() {
var metas = document.getElementsByTagName('meta');
for (var meta of metas) {
if (meta.getAttribute('http-equiv') === 'Content-Security-Policy') {
var nonceRe = /'nonce-([^']+)'/;
var matches = meta.getAttribute('content').match(nonceRe);
var nonce = matches[1];
if (nonce && testNonce(nonce)) {
return matches[1];
}
}
}
var scripts = document.getElementsByTagName('script');
for (var script of scripts) {
if (script.hasAttribute('nonce')) {
var nonce = script.getAttribute('nonce');
if (testNonce(nonce)) {
return nonce;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment