5

I am trying to make a to-do application in pure HTML5 and Javascript and I have come across the problem of sanitizing the input.

For eg: If user enters <script>alert("XSS")</script>, the code is executed on the page.

Code for adding an element is:

if ($('#TextArea').val() !== "") {
  var taskID = new Date().getTime();
  var taskMessage = $('#textArea').val();
  localStorage.setItem(taskID, taskMessage);
}

while the code for displaying the elements is:

var i = 0;
for (i = localStorage.length; i != 0; i--) {
  var taskID = localStorage.key(i - 1);
  $('#task').append("<li id='" + taskID + "'>" + localStorage.getItem(taskID) + "</li>");
}

Is there any way to sanitize the data using only HTML5 and Javascript properties?

Tomalak
  • 332,285
  • 67
  • 532
  • 628
Dvorak
  • 169
  • 1
  • 2
  • 11

1 Answers1

7

As with any and all XSS prevention: Don't build HTML from strings, especially not when those strings contain user-supplied values.

jQuery has a convenient facility to build elements safely - you can pass in an object with properties:

$("<li>", {
  id: taskID,
  text: localStorage.getItem(taskID)
}).appendTo('#task');

In fact, I recommend that you absolutely never use string concatenation to build HTML. For more complex situations than the above, use a well-tested HTML templating library like Mustache or Handlebars.

Tomalak
  • 332,285
  • 67
  • 532
  • 628
  • 1
    You can't nest an `
  • ` inside an ``, so let's do it the other way around: `$("
  • ").append( $("", {href: "something", text: "something"}) );`. This gets tedious very fast, that's why I recommended a templating engine. Compare a few and pick up one you like.
  • – Tomalak Aug 04 '15 at 15:29
  • But sir, if I have to use the above code: `$("
  • ", {id: taskID,text:localStorage.getItem(taskID)}).appendTo('#task');` with `$("
  • ").append( $("", {href: "something", text: "something"}) );`, how can we do so?
  • – Dvorak Aug 04 '15 at 16:55