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