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); |
not sure why var attrName = this.name;
would be necessary in trimAttributes. It simply makes an alias, you can use the this.name
stance everywhere with the same efficiency
Unfortunately, using jQuery to sanitize HTML in order to prevent XSS is not safe, as jQuery is not just parsing the HTML, but actually creating elements out of it. Even though it doesn't insert these into the DOM, in some cases embedded Javascript will be executed. So, for example, the snippet:
$('<img src="http://i.imgur.com/cncfg.gif" onload="alert(\'gotcha\');"/>')
use @kaznum 's sanitizer for example
// XSS!
sanitizer.sanitize('<img src=1 onerror=alert(1)>');
Also use DOM for example
// XSS!
document.createElement('div').innerHTML = '<img src=1 onerror=alert(1)>';
If you want sanitize HTML with jQuery prevent Application from XSS attacks, you must use jQuery 3.0+, see demo jquery-sanitize-html.html
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this fails to remove script tags.