通常是用来接收用户输入,用于提交到服务器端,例如 网站的评论框。javascript
若是此框也用于显示服务器端回传的内容,则有以下两种用法html
法1 后台直接插入java
<textarea><%=serverString;%></textarea>jquery
法2 使用JS DOM接口赋值ajax
textareaDom.value = "<%=serverString;%>"服务器
即法1特性, 即便将html代码段插入textarea, html代码段不会执行, 仅仅将其做为普通文本显示。网站
<html>
<head>
</head>
<body>
<textarea>ui<script>alert("aa")</script>
<div>bbb</div>spa</textarea>
</body>
</html>code
将HTML代码贴到此网站的编辑框中,点击运行看效果。
http://www.tool.la/WebEditor02/
不一样于其余标签,例如div, 其内容内嵌script脚本,会被执行,
尽管textarea不会执行script,其仍然可遭受XSS攻击。
在插入textarea内容时候,提早关闭标签,而后输出script脚本,以下
<html> <head> </head> <body> <textarea>
</textarea><script>alert("aa")</script>
</textarea> </body> </html>
HTML规范要求,内容中不能有闭合标签。
http://www.w3.org/TR/html-markup/syntax.html#contents
An end tag that is not contained within the same contents as its start tag is said to be a misnested tag.
规范上要求的 textarea content 内容为 replaceable character data
http://www.w3.org/TR/html-markup/textarea.html
这种字符类型,要求内容中不能有标签闭合的字符:
http://www.w3.org/TR/html-markup/syntax.html#replaceable-character-data
must not contain any occurrences of the string "
</
" followed by characters that are a case-insensitive match for the tag name of the element containing the replaceable character data (for example, "</title
" or "</textarea
"), followed by a space character, ">
", or "/
".
对于法1 须要实施HTML转码,将</sss>转换为 <;
<textarea><%=encodeHTML(serverString);%></textarea>
对于法2 须要实施JS转码
textareaDom.value = "<%=encodeJS(serverString);%>"
若是您的后台不支持转码,能够使用法2+ajax获取方式:
一、 将显示的数据存储为后台文件(logstr.txt), 例如文件内容为,含有攻击脚本,使用法1会构成XSS攻击:
</textarea><div>aa</div><script>alert("aa")</script>
二、使用ajax获取此文件内容, 后调用法2接口给textarea赋值。
<html> <head> <script src="./jquery.js"></script> </head> <body> <textarea id="test"> </textarea> <script type="text/javascript"> $.get("./logstr.txt", {Action:"get",Name:"lulu"}, function (data, textStatus){ document.getElementById("test").value = data; }); </script> </body> </html>