deidara song
deidara song

Reputation: 209

How do i prevent html/javascript code from running on a textbox

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

Upvotes: 2

Views: 2409

Answers (3)

Konstantin Dinev
Konstantin Dinev

Reputation: 34895

Your general encode procedure here would be:

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

Upvotes: 1

ViROscar
ViROscar

Reputation: 148

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.

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324610

I just use this:

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

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

Upvotes: 7

Related Questions