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开发者_如何学Python?
You need to encode the tags:
<textarea>
<script type="text/javascript"></script>
</textarea>
In PHP, you can do this with htmlentities()
.
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 < = < and > = >
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.
精彩评论