Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML entities inside script tag not converted?

Tags:

<script type="text/javascript">     function test()    {         alert('&lt;span&gt;blah&lt;span&gt;');     } </script> <a href="#" onclick="test();">First</a><br /> <a href="#" onclick="alert('&lt;span&gt;blah&lt;span&gt;');">Second</a><br /> Third: &lt;span&gt;blah&lt;span&gt; 

Demo: http://jsfiddle.net/LPYTZ/

Why is the first result different? Are <script> tags somehow excluded from entity conversion?

like image 597
AndreKR Avatar asked Nov 19 '10 17:11

AndreKR


2 Answers

In HTML, script and style elements are defined in the DTD as containing CDATA. This means that entities and tags are ignored until the parser hits something that looks like an end tag.

XHTML is different and entities and tags inside those elements function as normal — but only when parsed as XHTML. You can explicitly mark content as CDATA with <![CDATA[ … ]]>.

Browsers will treat XHTML served as text/html using HTML rules which leads to a big ball of nasty as you try to write code that is correct under both sets of rules.

The simplest way to avoid problems is to keep scripts in external files and use the src attribute to include them.

like image 104
Quentin Avatar answered Sep 30 '22 20:09

Quentin


Yes, the content model of STYLE and SCRIPT is special:

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.

like image 32
Gumbo Avatar answered Sep 30 '22 22:09

Gumbo