Zach Brantmeier
Zach Brantmeier

Reputation: 746

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

Upvotes: 0

Views: 165

Answers (1)

Adam D. Ruppe
Adam D. Ruppe

Reputation: 25605

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.

Upvotes: 1

Related Questions