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?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Sir, if I have to insert an anchor tag, such that <a href="something"><li>something</li></a> , then how should I go on with that?
You can't nest an <li> inside an <a>, so let's do it the other way around: $("<li>").append( $("<a>", {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.
But sir, if I have to use the above code: $("<li>", {id: taskID,text:localStorage.getItem(taskID)}).appendTo('#task'); with $("<li>").append( $("<a>", {href: "something", text: "something"}) );, how can we do so?
$("<li>").append( $("<a>", {href: "something", text: "something"}) ).appendTo("#task");, if I understand you right. Itr seems like you are missing essential jQuery basics, please take some time to learn how jQuery works. It's not a good idea to use a library that you don't really understand.
No sir, I understood that part. Actually, if you will see this: jsfiddle.net/bwk54ma2/1 . What I am unable to do is that, I also want <li> to have id=taskID (such that <li id=taskID><a href=taskID>Something</a></li>), and I can't nest that property.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.