Skip to content

Instantly share code, notes, and snippets.

@diogoalexsmachado
Created April 22, 2021 15:53
Show Gist options
  • Save diogoalexsmachado/8f8cb0e536f54bd5973962978e172ec0 to your computer and use it in GitHub Desktop.
Save diogoalexsmachado/8f8cb0e536f54bd5973962978e172ec0 to your computer and use it in GitHub Desktop.
/*
* 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