Skip to content

Instantly share code, notes, and snippets.

@kaznum
Created October 1, 2012 08:16
Show Gist options
  • Save kaznum/3810258 to your computer and use it in GitHub Desktop.
Save kaznum/3810258 to your computer and use it in GitHub Desktop.
sanitize HTML with jQuery
/*
* 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);
@ralyodio
Copy link

this fails to remove script tags.

@genee19
Copy link

genee19 commented Aug 27, 2014

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

@ufologist
Copy link

Given a string of html code, how can I go through every tag and remove ones that is not in my whitelist (in JQuery)?

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