Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing HTML and Script injections in Javascript

Assume I have a page with an input box. The user types something into the input box and hits a button. The button triggers a function that picks up the value typed into the text box and outputs it onto the page beneath the text box for whatever reason.

Now this has been disturbingly difficult to find a definitive answer on or I wouldn't be asking but how would you go about outputting this string:

<script>alert("hello")</script> <h1> Hello World </h1> 

So that neither the script is executed nor the HTML element is displayed?

What I'm really asking here is if there is a standard method of avoiding both HTML and Script injection in Javascript. Everyone seems to have a different way of doing it (I'm using jQuery so I know I can simply output the string to the text element rather than the html element for instance, that's not the point though).

like image 756
lorless Avatar asked Dec 31 '13 10:12

lorless


People also ask

How can you prevent script injection that was pasted to input?

You can paste anything you like into an input field, and submit it to a server. Pasting <script>alert("hi");</script> into an input is fine, and that text will be used as the value of the input field when the form data is submitted to the server.

What is JavaScript injections?

A JavaScript injection attack is a type of attack in which a threat actor injects malicious code directly into the client-side JavasScript. This allows the threat actor to manipulate the website or web application and collect sensitive data, such as personally identifiable information (PII) or payment information.

How can we prevent HTML injection in Java?

General advices to prevent InjectionApply Input Validation (using "allow list" approach) combined with Output Sanitizing+Escaping on user input/output. If you need to interact with system, try to use API features provided by your technology stack (Java / . Net / PHP...) instead of building command.

What is a HTML injection?

What is HTML Injection. HTML Injection also known as Cross Site Scripting. It is a security vulnerability that allows an attacker to inject HTML code into web pages that are viewed by other users.


1 Answers

You can encode the < and > to their HTML equivelant.

html = html.replace(/</g, "&lt;").replace(/>/g, "&gt;"); 

How to display HTML tags as plain text

like image 106
TastySpaceApple Avatar answered Sep 29 '22 11:09

TastySpaceApple