Created
January 15, 2014 00:56
-
-
Save samgreen/8428912 to your computer and use it in GitHub Desktop.
Escaping with the DOM!
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
// 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 : ''; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Interesting