简体   繁体   中英

HTML Encode the content of input type text (TextBox) in client side (using Jquery etc)

I am using Ajax to post the comments of the website.

No the user can also write some scripts inside a textbox.

The problem is I want to HTML encode it (REMOVE html tags,scripts ETC) .

Means remove the html elements.

As far as now i make an unsuccessful try as:

 var textData = $("'" +  $('#textBox').val() + "'").text();

But this is a ridiculous attempt by me. Though it sometimes work but it MAY fail with special symbols etc.

Any help is this regard is deeply appreciated.

Thank You.

EDIT:

Whenever the user post the comment i send the comment to server and at the server side encode it and save it to DB and also on client side update my HTML. I dont want to get the encoded message back from the server

As everyone else said, please don't do this. Solve it on the server.

However, the shortest way to just HTML encode whatever was send (that is, actually print out <b>x</b> is this:

var yourText = $('#textbox').val(); // or whatever
var yourTextHTML = $('<span></span>').text(yourText).html();

You really shouldn't do this client-side. An attacker can just post a comment, intercept the request using a debugging tool such as Fiddler , modify it so it includes some forbidden characters - and you're XSS ed.

It is highly recommended that you do this at the server instead. Just pass each comment through htmlentities in PHP (or the equivalent function for whatever server-side scripting language you're using) before writing it to the document, this will render all XSS attempts useless.

You should do the encoding when you are displaying the comments in a blog page and not at the client side that will helps to avoid XSS attacks and others. Encoding is not about removing html, script tags but it is about representing the angle brackets as character entity names.

For ex.

you have written a nice article<script></script>

after encoded

"you have written a nice article&lt;script&gt;&lt;/script&gt;"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM