简体   繁体   English

检查Javascript字符串是否为HTML代码

[英]Checking if Javascript string is HTML code

I have a textbox and submit button which posts the content and a reply to the HTML page. 我有一个文本框和提交按钮,用于发布内容和对HTML页面的回复。 Is there any way (other than checking if the string's substring at the beginning is 有什么办法(除了检查字符串开头的子字符串是否为

    <h1>,<h2>,<h3>...,<script>,<style>,etc.

to see if a string will be formatted differently when it is posted on the page, in order to prevent code injection? 查看字符串在页面上发布时是否会以不同的格式设置,以防止代码注入?

Thanks 谢谢

-Zach -扎克

When you display user data, you should correctly encode it as html. 显示用户数据时,应正确地将其编码为html。 In javascript, use document.createTextNode(userData) and append that node instead of using innerHTML. 在javascript中,使用document.createTextNode(userData)并附加该节点,而不是使用innerHTML。 In PHP, use htmlentities . 在PHP中,使用htmlentities

If the user is allowed to use any html or formatting, you should do them with a strict whitelist of allowed tags and attributes, and encode everything else as plain text. 如果允许用户使用任何html或格式,则应使用允许的标签和属性的严格白名单对他们进行处理,并将其他所有内容编码为纯文本。

So, even if the user did enter <h1>stuff</h1> , when that's properly encoded, it will come out as &lt;h1&gt;test&lt;/h1&gt; 因此,即使用户确实输入了<h1>stuff</h1> ,当对其进行正确编码时,它也会以&lt;h1&gt;test&lt;/h1&gt; instead of html, which won't be vulnerable to javascript injection. 而不是html,因为它不会受到javascript注入的攻击。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM