避免在维护HTML的同时注入JavaScript? [英] avoid javascript injection while maintaining HTML?
问题描述
$("#id").append(dataHtml);
当注入<script>alert('test)</script>
时,一个警告框出现在显示test的屏幕上.我对html进行了编码,但随后显示为纯文本.
我从数据库中获得了dataHtml的值.由于某些原因,我必须使用javascript/jquery在客户端进行所有操作.
在维护html时如何忽略此类标记/注入?
您可以使用简单的正则表达式删除所有脚本标签:
dataHtml = dataHtml.replace(/<script.*>[\s\S]*.*[\s\S]*<\/script>/g,"");
一些解释:
-
.*
:除换行符外的所有字符(*次) -
[\s\S]*
:换行符
要测试所有内容是否符合预期,可以使用带有dataHtml值示例的在线工具( http://例如www.regexr.com/.
$("#id").append(dataHtml);
when injected with <script>alert('test)</script>
an alert box appears on the screen showing test.I encoded the html but then it appeared as plain text.
I get the value of dataHtml from database.Because of some reasons I have to do this all on the client side using javascript/jquery.
How do i ignore such tags/injection while maintaing the html?
you could just use a simple regular expression to remove all script tags:
dataHtml = dataHtml.replace(/<script.*>[\s\S]*.*[\s\S]*<\/script>/g,"");
some explanation:
.*
: all characters except linebreaks (* times)[\s\S]*
: linebreaks
to test if everything matches as expected you can use an online tool with an example of your dataHtml value (http://www.regexr.com/ for example).
这篇关于避免在维护HTML的同时注入JavaScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!