简体   繁体   中英

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. 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. In javascript, use document.createTextNode(userData) and append that node instead of using innerHTML. In PHP, use 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.

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; instead of html, which won't be vulnerable to javascript injection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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