Skip to content

Instantly share code, notes, and snippets.

@joeytwiddle
Last active May 31, 2016 01:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joeytwiddle/763b66270e234518193c to your computer and use it in GitHub Desktop.
Save joeytwiddle/763b66270e234518193c to your computer and use it in GitHub Desktop.
// 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>';
}
@joeytwiddle
Copy link
Author

@joeytwiddle
Copy link
Author

joeytwiddle commented Mar 10, 2016

  • 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...

@joeytwiddle
Copy link
Author

joeytwiddle commented May 1, 2016

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