1

Take for example this HTML:

<td onclick="$(this).html('Wanted HTML: <br>; Unwanted HTML: &lt;script&gt;alert(&#39;xss&#39;)&lt;/script&gt;')">
Click to Show</td>

As you can see, I have already escaped (using PHP) the unwanted HTML to entities. But when you click the box it executes the JavaScript.

If I change .html to .text, it displays the line breaks literally as well.

How can I have it show the the <br>s as line breaks, but the &lt;s and &gt;s as literally less than and greater than signs when you click the box?

4

1 回答 1

2

The problem is that your characters are being decoded in the onclick, before they reach the JavaScript function.

You need to double-encode. So your example would become:

<td onclick="$(this).html('Wanted HTML: &lt;br&gt;; Unwanted HTML: &amp;lt;script&amp;gt;alert(&amp;#39;xss&amp;#39;)&amp;lt;/script&amp;gt;')">
    Click to Show
</td>

Notice that I encoded (single encoded) the tags you do want. I also added the missing semicolon on the first &gt;.

Of course the better solution is to remove this from the HTML entirely. Most developers agree that JavaScript is for interactivity and HTML is for content, and they should mix as little as possible (with the JavaScript hooking into the content with calls such as addEventHandler)

于 2013-03-30T02:50:22.330 回答