Tag Archives: html

Putting HTML in inline JavaScript

A tag inside inline JavaScript string literal is interpreted by the HTML parser as a closing tag, causing syntax errors.
According to w3.org

Although the STYLE and SCRIPT elements use CDATA for their data model, for these elements, CDATA must be handled differently by user agents. Markup and entities must be treated as raw text and passed to the application as is. The first occurrence of the character sequence “</” (end-tag open delimiter) is treated as terminating the end of the element’s content. In valid documents, this would be the end tag for the element.

In real world scenario web browsers only end parsing a CDATA script block on an actual close-tag.
Unfortunately, there is no such special handling for script blocks in XHTML, causing < (or &) character to generate syntax errors if it is not properly escaped (i.e. HTML entity encoded).
There are different approaches to avoid such problems:

1) Encode the HTML string in base64 and decode it when reading
2) Split the <script> tag like that

var str = '</' + 'script' + '>';

3) Use CDATA

<script type="text/javascript">
//<![CDATA[
...code...
//]]>
</script>