How to escape values for inline scripts?

30 views
Skip to first unread message

Mikhail Trishchenkov

unread,
Jan 17, 2013, 1:51:03 AM1/17/13
to play-fr...@googlegroups.com
I have variable with JSON string

val json = """ "text" """

which I want to use in inline script tag:

<script type="text/javascript">
 
var a = @json;
</script>

However, this will turn special characters to entities:

var a = &quot;text&quot;

and because "script" and "style" tags implicitly have CDATA content type, entities won't be decoded.

But using @Html(json) is unsafe, because json variable may content "</script>" which will cause browser to stop parsing script tag and threat the rest as HTML.

One possible solution is to include data from external script file, but it is additional request to server for very small chunk of data.
Another is to put JSON to hidden tag: <div id="data" style="display: none;">@json</div> and then take it as JSON.parse(document.getElementById('data').innerText), but it's ugly.

Is there better solution?

Reply all
Reply to author
Forward
0 new messages