views:

758

answers:

3

Hello, I'm using a json object to store different bits of content, one of which can contain javascript & html relevant content (like quotes, semicolons, tags etc) which without encoding can break the page. To work around this I'm using:

"content":"<%=StringEscapeUtils.escapeHtml(StringEscapeUtils.escapeJavaScript(content))%>"

(I'm using JSP as server-side technology and this is a bit of the JSON generated inline when the page is loading)

This works fine to escape any character that might break the page, but I now need to get the content from this variable to a textarea.

$('textarea').val(obj.content);

What I'm trying to avoid is the double-encoding that happens at this point:

  • the original content is: <script>alert("hello world");</script>
  • the content variable holds: &lt;script&gt;alert(&quot;hello world&quot;);&lt;/script&gt;
  • the text in the textarea reads: &lt;script&gt;alert(&quot;hello world&quot;);&lt;/script&gt; when it should read <script>alert("hello world");</script>

Any way of making this work?

A: 

Just put it in unescape. I mean $('textarea').val(unescape(obj.content));

Eldar Djafarov
unescape() has no effect on the content.
Dan
Yes you are rigth:( sorry - than you need to htmp entity decode manually.
Eldar Djafarov
A: 

Would you be able to use StringEscapeUtils.escapeJavaScript instead? If the JSON is in a <script> block that should be sufficient to avoid breaking the page and no decoding will be necessary.

Nate
That's how it was originally, but because there exists the unencoded "</script>" element in my content, it prematurely closes the <script> containing the JSON.
Dan
But of course...
Nate
A: 

How about $('textarea').html(obj.content); ?

In my tests, using the html function instead of val does the HTML entity decoding for you.

npdoty