Skip to content

Instantly share code, notes, and snippets.

@samgreen
Created January 15, 2014 00:56
Show Gist options
  • Save samgreen/8428912 to your computer and use it in GitHub Desktop.
Save samgreen/8428912 to your computer and use it in GitHub Desktop.
Escaping with the DOM!
// This will use the browser's ability to determine if text needs to be escaped
function escapeHtml(untrustedString) {
// Create a new div
var div = document.createElement('div');
// Create a new text node (using innerHTML would give us the same problem).
var node = document.createTextNode(str)
// Append the text node to the div
div.appendChild(node);
// Return the properly escaped HTML
return div.innerHTML;
};
// This will create the same XSS problem if used incorrectly
function unescape(escapedString) {
// Create a new div
var div = document.createElement('div');
// Set the HTML of the div to the escaped string
div.innerHTML = escaped;
// Return the valid nodeValue or an empty string
return div.childNodes[0] ? div.childNodes[0].nodeValue : '';
};
@coffeebite
Copy link

Interesting

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment