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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With