Search code examples
jsf-2faceletscdatajsf-2.2

JSF 2.2 CDATA is escaped


I have found some weird behaviour after upgrading to Mojarra 2.2.3. The following Javascript declaration gets mangled:

In the .xhtml file:

<script type="text/javascript">
<!-- /* <![CDATA[ */
    $(document).ready(function() {                                                                             
        if ($('#some_identifier').size() > 0) 
        ...
/* ]]> */-->
</script>

This is mangled into the following nonsense:

<script type="text/javascript">
<!-- /* &lt;![CDATA[ */
    $(document).ready(function() {
        if ($('#some_identifier').size() &gt; 0)
        ...
/* ]]&gt; */-->
</script>

This breaks all javascript code embedded in .xhtml files. I verified that this does not happen with the versions we used previously (2.0.x), so I must assume it's got something to do with the new Mojarra version. Any ideas on how to fix this or work around it?


Solution

  • This CDATA syntax is completely invalid. It's not clear where you got this from and why you thought it would be valid. Perhaps you confused it with CDATA syntax for CSS code. In any case, for proper CDATA syntax in JS code, carefully read this Mozilla Developer Network article: Writing JavaScript for XHTML.

    The valid (modern) syntax is:

    <script type="text/javascript">
      <![CDATA[
        $(document).ready(function() {                                                                             
          if ($('#some_identifier').size() > 0) 
            ...
      ]]>
    </script>
    

    If you really, really need to support old browsers which no one on the world uses, then use the following syntax which should work in those browsers which doesn't natively support JavaScript and therefore are incapable of parsing <script> elements (wonder yourself, would your JSF application, rich of JavaScript, still work on those webbrowsers? would it really be useful to escape JS for them as well?)

    <script type="text/javascript">
      <!--//--><![CDATA[//><!--
        $(document).ready(function() {                                                                             
          if ($('#some_identifier').size() > 0) 
            ...
      //--><!]]>
    </script>
    

    By the way, much better is to put that JS code in its own .js file.

    See also: