Skip to content

Instantly share code, notes, and snippets.

@jonathantneal
Last active February 25, 2019 13:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonathantneal/0cae0ca01612236a1d0634171830c311 to your computer and use it in GitHub Desktop.
Save jonathantneal/0cae0ca01612236a1d0634171830c311 to your computer and use it in GitHub Desktop.
Sanitize a document or element using a whitelisted selectors and whitelisted attributes
// sanitize an element using a whitelisted selector string
function sanitizeDOM(ELEMENT, WHITELISTED_SELECTORS, WHITELISTED_ATTRIBUTES) {
// get all elements within an ELEMENT
Array.prototype.forEach.call(ELEMENT.querySelectorAll('*'), node => {
// if the element does not match a WHITELIST_SELECTOR_STRING
if (!node.matches(WHITELISTED_SELECTORS)) {
// create a new document fragment
const fragment = document.createDocumentFragment();
// append all the children of the invalid node into the new fragment
Array.prototype.forEach.call(node.childNodes, childNode => {
fragment.appendChild(childNode);
});
// sanitize the fragment
sanitizeDOM(fragment, WHITELISTED_SELECTORS)
// replace the invalid node with the sanitized fragment
node.parentNode.replaceChild(fragment, node);
} else if (node.attributes) {
// otherwise, get all the attributes on the node
Array.prototype.forEach.call(node.attributes, attribute => {
// if the attribute is not whitelisted
if (!WHITELISTED_ATTRIBUTES.includes(attribute.name)) {
// remove the attribute from the node
node.removeAttributeNode(attribute);
}
})
}
})
}
// const ELEMENT = document;
// const WHITELISTED_SELECTORS = 'h1, h2, h3, p, p strong, p em';
// const WHITELISTED_ATTRIBUTES = ['class', 'style']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment