在Javascript中防止HTML和脚本注入 [英] Preventing HTML and Script injections in Javascript

查看:100
本文介绍了在Javascript中防止HTML和脚本注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个带有输入框的页面。用户在输入框中输入内容并点击按钮。该按钮会触发一个函数,该函数会将输入到文本框中的值输出到文本框下面的页面中,无论出于何种原因。



现在这已经非常困难了找到一个明确的答案或我不会问,但你会怎么去输出这个字符串:

 < script> ;警报( 你好)LT /脚本> < H1> Hello World< / h1> 

既不执行脚本也不显示HTML元素?



我真正要问的是,如果在 Javascript 中有避免HTML和Script注入的标准方法。每个人似乎都有不同的做法(我使用jQuery,所以我知道我可以简单地将字符串输出到 text 元素而不是 html 元素,但这不是重点)。

解决方案

您可以编码< > 到它们的HTML equivelant。
$ b

  html = html .replace(/< / g,& lt;)。replace(/> / g,& gt;); 

如何将HTML标签显示为纯文本


Assume I have a page with an input box. The user types something into the input box and hits a button. The button triggers a function that picks up the value typed into the text box and outputs it onto the page beneath the text box for whatever reason.

Now this has been disturbingly difficult to find a definitive answer on or I wouldn't be asking but how would you go about outputting this string:

<script>alert("hello")</script> <h1> Hello World </h1>

So that neither the script is executed nor the HTML element is displayed?

What I'm really asking here is if there is a standard method of avoiding both HTML and Script injection in Javascript. Everyone seems to have a different way of doing it (I'm using jQuery so I know I can simply output the string to the text element rather than the html element for instance, that's not the point though).

解决方案

You can encode the < and > to their HTML equivelant.

html = html.replace(/</g, "&lt;").replace(/>/g, "&gt;");

How to display HTML tags as plain text

这篇关于在Javascript中防止HTML和脚本注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆