46

I am encountering an issue where having a ending script tag inside a quoted string in JavaScript, and it is killing the script. I assume this is not expected behaviour. An example of this can be seen here: http://jsbin.com/oqepe/edit

My test case browser for the interested: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.4) Gecko/20091028 Ubuntu/9.10 (karmic) Firefox/3.5.4.

0

2 Answers 2

88

What happens?

The browser HTML parser will see the </script> within the string and it will interpret it as the end of the script element.

Look at the syntax coloring of this example:

<script>
var test = 'foo... </script> bar.....';
</script>

Note that the word bar is being treated as text content outside of the script element...

A commonly used technique is to use the concatenation operator:

var test = '...... </scr'+'ipt>......';
Sign up to request clarification or add additional context in comments.

5 Comments

This does work, but I am surprised that I have to do it. Part of the problem is that I am scraping a page and storing the results in a JS variable. I have no real expectations of what Is coming back.
How are you storing it in a variable? Are you scraping server-side then generating var x = <string>;? If so, don't forget to JSON-encode it.
Escape the /, don't split the string up into parts. IIRC it is still an error in HTML 4.x. It is certainly more fiddly to type, messier to read, more characters to deal with, and less efficient (since string concatenation isn't the cheapest of JS operations)
Yeap, only what you need to do is add a back slash var t = 'my tag <\/script> for script';
this is such a counterintuitive security flaw. in fact, this is an XSS vulnerability and should be prevented by following the rules, not just some "split-in-the-middle".
17

You need to escape it, else it will be a part of the HTML.

var test = 'what the hell... \<\/script\> \<h1\>why?!?!?!\<\/h1\>';

4 Comments

It's the way XML is being rendered. You can also wrap the script with <![CDATA[ and ]]>. It won't happen with other tags because the way the XML parser work (notably it treats script as text, and not as code).
@LiraNuna Umm. No. An XML parser will treat </script> as "End of script" and </notscript> as a well-formness error. An HTML parser will treat </anything> as "end of script" and then if it is </notscript> as "Error with handling undefined by the specification". Only a tag soup parser (and possibly an HTML5 parser, I haven't read the draft closely enough to be sure) will treat </notscript> as part of the script.
Oh, and if you wrap with CDATA markers then that won't fix it for tag soup parsers.
Nice solution the escaping, but really not needed for anything but the script tag's slash.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.