1

I'm having an issue where I'm trying to use JQuery to append a string to a div.

This string will be HTML, and occassionally users will be using the script tags inside the string.

Unfortunately, when the browser reads </script> inside the string, it ends the section and prints out all the following javascript into the browser. Obviously, we don't want that.

Is there a way to get the browser to not parse anything inside the string?

An example of this might be an Adsense ad being appended to the div.

jrummell
  • 42,637
  • 17
  • 112
  • 171
user1146223
  • 209
  • 4
  • 14
  • 3
    Please add jsfiddle link – MIIB Mar 06 '13 at 20:21
  • 2
    Please show some code. – jrummell Mar 06 '13 at 20:21
  • Note, if an adsense ad is appended to an already loaded page, your already loaded page will be nuked due to `document.write`, though since you're freely allowing javascript, they could do that directly too. – Kevin B Mar 06 '13 at 20:23
  • 3
    You can just escape the slash in the string: `"<\/script>"`. See: http://stackoverflow.com/questions/14884134/script-script-tags-inside-of-javascript-code/14885679#14885679 – ZER0 Mar 06 '13 at 20:25

2 Answers2

5

You can use a backslash (\) to escape the slash in the <script> close tag so that it doesn't close the actual <script> element:

var foo = document.write('<script src="somewhere.js"><\/script>');

This is often used when loading a script from a CDN with a local fallback:

<script src="//cdn.example.com/jquery.js"></script>
<script>
    if (!window.jQuery) document.write('<script src="/assets/js/jquery.js"><\/script>');
</script>
zzzzBov
  • 174,988
  • 54
  • 320
  • 367
1

The workaround way for the problem is using:

"</scr"  + "ipt>"

Ugly, annoying, but working!

gdoron
  • 147,333
  • 58
  • 291
  • 367