2

I had a text box in my browser. Whatever you typed in the text box and clicked on okay button, the text submitted server through a AJAX request and then spread that message to remaining people, including to me also.

The message is appeared on a <div>.

What's my problem is if I typed html or script tags in that message they are not appearing in the message <div> and they are executing .

If I typed like tags opened and end with script in that middle code is executing on client side, how can I prevent executing and I am able to spread <script> tags also in the messages spreading to all.

3
  • 1
    Handle your text as text, not HTML. Commented Mar 26, 2011 at 6:05
  • @alex Indeed. Consider an answer ;-) Commented Mar 26, 2011 at 7:15
  • @psd Thanks, and OK, I shall write one. Commented Mar 26, 2011 at 7:19

2 Answers 2

2

If you want the text to always be text, treat is as text and don't use it to set innerHTML property for example.

Update text nodes instead.

Update

For example, if you had user input in userInput, and you wanted to display it, you would treat it as text, not HTML.

var element = document.body,
    // For example
    userInput = "Alex <script>alert('xss')</script>";

// Don't do this! Your input is text, not HTML.
// element.innerHTML = userInput;

// Use this instead
if ('textContent' in element) {
    element.textContent = userInput;
} else {
    element.innerText = userInput;
}

jsFiddle.

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

5 Comments

thanks @alex .but i did'nt understood .you only understood my problem ..please give me in breif ..please .please
use it to set innerHTML property for example. what is means ?? and how to update text nodes instead .
@suresh See update. You will need to do a little research by yourself as well.
and one more doubt ...if(textContent in element) ..what does that special symbols above text content shown??
@suresh See updated code, I accidentally used backticks as string delimiters :)
2

Have you tried replacing with html character entities? For example replacing all < with &lt;.

Comments

Your Answer

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