avoid javascript injection while maintaining HTML?

别来无恙 提交于 2019-12-11 09:42:19

问题


 $("#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?


回答1:


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).




回答2:


Append the script element with the type attribute set to something other than text/javascript, i.e. like this:

<script type="text/template">alert('test');</script>

This script tag will not be parsed or run as javascript.



来源:https://stackoverflow.com/questions/26054877/avoid-javascript-injection-while-maintaining-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!