Skip to content Skip to sidebar Skip to footer

Prevent User-entered Scripts From Running In Webpage

In my application, there is a comment box. If someone enters a comment like then an alert appears when I load that page. Is there an

Solution 1:

There are several ways to address this, but since you haven't mentioned which back-end technology you are using, it is hard to give anything but rough answers.

Also, you haven't mentioned if you want to allow, or deny, the ability to enter regular HTML in the box.

Method 1:

Sanitize inputs on the way in. When you accept something at the server, look for the script tags and remove them.

This is actually far more difficult to get right then might be expected.

Method 2:

Escape the data on the way back down to the server. In PHP there is a function called htmlentities which will turn all HTML into which renders as literally what was typed.

The words <script>alert("hello")</script> would appear on your page.

Method 3

White-list

This is far beyond the answer of a single post and really required knowing your back-end system, but it is possible to allow some HTML characters with disallowing others.

This is insanely difficult to get right and you really are best using a library package that has been very well tested.

Solution 2:

You should treat user input as plain text rather than HTML. By correctly escaping HTML entities, you can render what looks like valid HTML text without having the browser try to execute it. This is good practice in general, for your client-side code as well as any user provided values passed to your back-end. Issues arising from this are broadly referred to as script injection or cross-site scripting.

Practically on the client-side this is pretty easy since you're using jQuery. When updating the DOM based on user input, rely on the text method in place of the html method. You can see a simple example of the difference in this jsFiddle.

Solution 3:

The best way is replace <script> with other string.For example in C#use:

str.replace("<script>","O_o");

Other options has a lot of disadvantage.

1.Block javascript: It cause some validation disabled too.those validation that done in frontend.Also after retrive from database it works again.I mean attacker can inject script as input in forms and it saved in database.after you return records from database in another page it render as script!!!!

2.render as text. In some technologies it needs third-party packages that it is risk in itself.Maybe these packages has backdoor!!!

Solution 4:

convert value into string ,it solved in my case

example

var anything

Post a Comment for "Prevent User-entered Scripts From Running In Webpage"