2

I have a chat application wirtten in javascript, when a user enters an html code like

 <button>click</button> 

a button appears on chat. I use this code

 if(message.indexOf('<button') != -1)
            {   
              message = message.replace(message, '&#45;'); 
            }

but this just replaces the < button

with a blank space, I want it to be displayed as text and not an actual button.

Thanks

1
  • 1
    That you have a chat application implies you've got serverside processing going on. Don't bother trying to amend the code at the upload stage (it's trivial to bypass and to run arbitrary javascript on a receivers machine). Clean the datastream on the server before re-broadcasting it. Commented Jul 16, 2012 at 15:01

3 Answers 3

7

I just use this:

message = message.replace(/</g,"&lt;");

That's all that's needed to prevent HTML from being inserted.

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

Comments

1

Your general encode procedure here would be:

value = value.toString().replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/'/g, "&#39;").replace(/"/g, "&#34;");

1 Comment

Chain anything else you would like to encode, e.g. ampersand.
0

what html element did you use for print the chat? try use textarea or pre tag.

try to control those errors in the back end because everybody can deactivate javascript.

Comments

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.