Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How come when I display JavaScript in a TextArea, it executes?

When there are <script> tags as the Textarea value, it executes the script.

Is there a way to prevent this?

like image 469
Shamoon Avatar asked Dec 27 '22 20:12

Shamoon


2 Answers

You need to encode the tags:

<textarea>
&lt;script type=&quot;text/javascript&quot;&gt;&lt/script&gt;
</textarea>

In PHP, you can do this with htmlentities().

like image 124
dtbarne Avatar answered Feb 23 '23 00:02

dtbarne


Because TextArea (<textarea>...</textarea>) is a node which can have inner nodes in it. The inner nodes are still valid so the browser interprets the script node and runs the code.

This is a really good reason why you should always validate what the user enters and posts to the server. If you display that input later, it can execute just like you meant to insert the script tag yourself.

To stop it you need to encode the tags < = &lt; and > = &gt;

A similar concept is having nodes which aren't valid html such as <myInvalidTag><script></script></myInvalidTag>. The browser will still execute the code inside it as well.

like image 31
kemiller2002 Avatar answered Feb 23 '23 00:02

kemiller2002