Question

There are no inline scripts involved, whatsoever. I have an external file script, which fetches some JSONP from twitter. Let's suppose that a property of the object represented in the returned JSONP was a string that contained somewhere in it the substring "</script>". Could this cause any problems on its own, without getting added to the DOM at all? (It gets scrubbed clean well before that point.)

I can't see why it would, but HTML parsing is notoriously whacky and quirky, so who knows? I know that if you want to have a string literal within an inline script, you need to break it up, like var slashScriptContainingString = 'foo</scr' + 'ipt>bar'; Again, I feel like it should be fine, but just checking to see if anyone knows why it might not be.

<!doctype html>
<script src="file.js"></script>

File.js:

var f = function(twobj) {
  console.log(twobj);
  doOtherStuffWith(twobj);
}

<script src="https://api.twitter.com/statuses/user_timeline/user.json?callback=f"></script>

Returned JSONP:

f(["this is an object, returned as part of the JSONP response, except it contains a string literal with the substring \"</script>\".  Is this a problem? Note: I haven't said anything about injecting this string in the DOM in any way shape or form. I can't think of a reason why it might be, but I'd just like to be sure."]);
Was it helpful?

Solution

No, string literals can contain whatever you want. As long as you are not blindly trying to set the innerHTML of something, a string is just a string. The example you have posted is safe.

The reason that you need to split up your </script> tag in your JavaScript source is that you are missing CDATA blocks. Without them, technically everything in your inline JavaScript needs to be properly escaped for HTML. (< becomes &lt;, etc.) Browsers are nice to you and let it slide, but </script> inside inline JavaScript becomes ambiguous. You should be using CDATA blocks to keep things like this from happening.

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

See this question for more details: When is a CDATA section necessary within a script tag?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top