Last active
December 23, 2015 09:19
-
-
Save csuwildcat/6613999 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var sanitize = (function(doc){ | |
var slice = Array.prototype.slice, | |
range = doc.createRange(), | |
frag = doc.createDocumentFragment(), | |
wrap = frag.appendChild(doc.createElement('div')); | |
function cleanNode(node, unwrap){ | |
var parent = node.parentNode; | |
if (unwrap){ | |
var next = node.nextElementSibling; | |
range.selectNodeContents(node); | |
parent[next ? 'insertBefore' : 'appendChild'](range.extractContents(), next); | |
} | |
parent.removeChild(node); | |
} | |
return function (html, options){ | |
wrap.innerHTML = html; | |
var options = options || {}, | |
grey = slice.call(wrap.querySelectorAll('*'), 0), | |
white = slice.call(wrap.querySelectorAll(options.whitelist ? options.whitelist : '*'), 0), | |
i = grey.length; | |
while (i--) { | |
if (white.indexOf(grey[i]) == -1) { | |
cleanNode(grey[i], options.unwrap); | |
} | |
} | |
return options.fragment ? range.selectNodeContents(wrap) || range.extractContents() : wrap.innerHTML; | |
}; | |
})(document); | |
var unsanitary = '<script src="foo.com/bar">alert("evil")</script><div>good<span>stuff</span></div>'; | |
sanitize(unsanitary, { | |
whitelist: ['div', 'span'], | |
fragment: false, | |
unwrap: true | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment