2

I have following page

<html>
<head>
    <script type="text/javascript" src="e01.js"></script>
</head>
<body>
<script type="text/javascript">
var obj={someHTML: "<script>alert('a');</script>rest of the html",  
               someOtherAttribute:"some value"};
    alert(obj.someHTML);
</script>
</body>
</html>

in someHTML attribute of my object I have </script> tag in a string. but browser reads this as actual close tag and closes the script element. is there anything I am missing here? (tried it in ff and chrome)

yilmazhuseyin
  • 6,442
  • 4
  • 34
  • 38
  • hey I found a bug in stackoverFlow. I cannot write in a regular text. it is working in comments but not in an actual question – yilmazhuseyin Aug 18 '10 at 07:46

4 Answers4

5

HTML is parsed before and independent from Javascript. The current browser behavior is that, once an open tag <script> is found, the browser will switch to "Script Data State" and interpret all following data as script until a </script> is found.

Where the </script> is detected doesn't matter — inside a JS string, a JS comment, a CDATA section, or even HTML comment.

You need to make the string does not look like </script> to the HTML parser. The simplest way is to write <\/script> as in @Daniel's answer.

Community
  • 1
  • 1
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
  • 1
    *Curious note:* Regarding the HTML4.01 spec, actually it should be the `ETAGO` sequence `` the token that would terminate a `SCRIPT` element's content, but seems that most browsers are permissive, and now the de-facto standard is `"';`... check [this test](http://kangax.github.com/jstests/etago_delimiter_test/). – Christian C. Salvadó Aug 18 '10 at 07:57
3

You may want to escape the script tag, like this: <\/script>

var obj= {
   someHTML: "<script>alert('a');<\/script>rest of the html",  
   someOtherAttribute: "some value"
};

Related post:

Community
  • 1
  • 1
Daniel Vassallo
  • 337,827
  • 72
  • 505
  • 443
3

You can either escape < and > by, respectively &lt; and &gt; or put the whole script in a CDATA section:

<script type="text/javascript">
<![CDATA[
var obj={someHTML: "<script>alert('a');</script>rest of the html",  
               someOtherAttribute:"some value"};
    obj(some.pageButtonScript);
]]>
</script>
Maurice Perry
  • 32,610
  • 9
  • 70
  • 97
0

Another way of doing it can be this.

 var obj= {
 someHTML: "<script>alert('a');</scr"+"ipt>rest of the html",  
 someOtherAttribute: "some value"
 };

just put a space between the ending script tag, so it wont be parsed as End tag.

Furqan Hameedi
  • 4,372
  • 3
  • 27
  • 34