Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sanitizing user input when creating HTML elements

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?

like image 773
Dvorak Avatar asked Aug 02 '15 08:08

Dvorak


1 Answers

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.

like image 191
Tomalak Avatar answered Sep 23 '22 20:09

Tomalak