Last active
May 31, 2016 01:37
-
-
Save joeytwiddle/763b66270e234518193c 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
// This code is not safe | |
function renderTemplate(user) { | |
return '<div>' | |
+ ' <div>' + user.name + '</div>' | |
+ ' <div>' + user.tel + '</div>' | |
+ '</div>'; | |
} | |
// Why not? | |
// Well, if user.tel is not sanitized, the user could inject unwanted HTML, for example: | |
// renderTemplate({name: "Bobby", tel: "<font size='+5' color='red'><a href="//mypillz.com">BUY VIAGRA HERE</a></font>"}); | |
// The solution is to encode the text before we insert it into the HTML. | |
// Here is the safe version. | |
function encodeForHTML(text) { | |
return document.createElement('div') | |
.appendChild(document.createTextNode(text)) | |
.parentNode.innerHTML; | |
} | |
function renderTemplate(user) { | |
var safe = encodeForHTML; | |
return '<div>' | |
+ ' <div>' + safe(user.name) + '</div>' | |
+ ' <div>' + safe(user.tel) + '</div>' | |
+ '</div>'; | |
} |
- But what if I want to do
return '<div data-item="' + encodeAttribute(JSON.stringify(itemData)) + '">Item</div>';
?
I don't have a function to encode attributes yet...
But anyway this approach of creating elements with jQuery and then turning them back to HTML again is not very efficient.
It could be more efficient to create all the elements in jQuery, and then let renderTemplate()
return an HTMLElement (or jQuery wrapped element), instead of returning a String.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Alternative encoder implementations
Discussion on encoder methods