Skip to content

Instantly share code, notes, and snippets.

@ScottHelme
Created February 26, 2020 09:52
Show Gist options
  • Save ScottHelme/261b1bb8547c4745748bece042c99ee2 to your computer and use it in GitHub Desktop.
Save ScottHelme/261b1bb8547c4745748bece042c99ee2 to your computer and use it in GitHub Desktop.
Detect SRI failures.
var observer = window.MutationObserver || window.WebKitMutationObserver;
if (observer) {
new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
mutation.addedNodes.forEach(processNode);
});
}).observe(document, { childList: true, subtree: true });
}
var processNode = function(node) {
var tagName = node.tagName ? node.tagName.toLowerCase() : '';
if (tagName === 'script' || tagName === 'link') {
if (!node.onerror) {
node.onerror = function(error) {
console.log("Got an error!");
console.log("Page: " + error.srcElement.baseURI);
console.log("Asset: " + error.srcElement.src);
console.log("Integrity: " + error.srcElement.integrity);
console.log("Element: " + error.srcElement.outerHTML);
console.log("Message: " /*+ ???*/);
console.log(error);
}
}
}
}
@ScottHelme
Copy link
Author

The intended purpose of the script is to reliably detect SRI failures on link and script tags.

I have a demo page setup here with an SRI failure for demonstration: https://scotthelme.co.uk/p/0576f1af-7540-49ba-9469-9e2a3fe1f634/

@ScottHelme
Copy link
Author

If you'd like info on what SRI is, see here: https://scotthelme.co.uk/subresource-integrity/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment