Created
October 1, 2012 08:16
-
-
Save kaznum/3810258 to your computer and use it in GitHub Desktop.
sanitize HTML with jQuery
This file contains 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
/* | |
* sanitize HTML with jQuery based on whitelist | |
* example: | |
* sanitizer.sanitize('<a href="foo" class="bar">aaa</a><script>alert("...")</script>', {'a': ['href'], 'strong': []}) | |
* returns '<a href="foo">aaa</a>' | |
*/ | |
var sanitizer = {}; | |
(function($) { | |
function trimAttributes(node, allowedAttrs) { | |
$.each(node.attributes, function() { | |
var attrName = this.name; | |
if ($.inArray(attrName, allowedAttrs) == -1) { | |
$(node).removeAttr(attrName) | |
} | |
}); | |
} | |
function sanitize(html, whitelist) { | |
whitelist = whitelist || {'font': ['color'], 'strong': [], 'b': [], 'i': [] }; | |
var output = $('<div>'+html+'</div>'); | |
output.find('*').each(function() { | |
var allowedAttrs = whitelist[this.nodeName.toLowerCase()]; | |
if(!allowedAttrs) { | |
$(this).remove(); | |
} else { | |
trimAttributes(this, allowedAttrs); | |
} | |
}); | |
return output.html(); | |
} | |
sanitizer.sanitize = sanitize; | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Given a string of html code, how can I go through every tag and remove ones that is not in my whitelist (in JQuery)?
use @kaznum 's sanitizer for example
Also use DOM for example
If you want sanitize HTML with jQuery prevent Application from XSS attacks, you must use jQuery 3.0+, see demo jquery-sanitize-html.html