dkris
dkris

Reputation: 1280

Formatting this JavaScript Line

I am trying to format this line of code in my popup window, but i am facing unterminated string literal error.

Can somebody please tell me how best I could format this.

window.setTimeout("winId.document.write('<script src="../js/tiny_mce/tiny_mce.js" type="text/javascript"></script>\n')", 10);

Also point out if this particular line of code would work fine in the popup?

Upvotes: 1

Views: 782

Answers (6)

Massimo Variolo
Massimo Variolo

Reputation: 4777

You can use this online tool: http://jsbeautifier.org/ best regards

Upvotes: 0

marapet
marapet

Reputation: 56516

You may try it by escaping the double-quotes and <>, as well as \n:

window.setTimeout("winId.document.write('\<script src=\"../js/tiny_mce/tiny_mce.js\" type=\"text/javascript\"\>\</script\>\\n')", 10);

Upvotes: 3

Matt
Matt

Reputation: 75317

Aside from you needing to escape your quotes (as other people have mentioned), you cannot include "</script>" (even if it's within a string) anywhere within a <script> tag

Use:

window.setTimeout(function () {
    winId.document.write(
      '<script src="../js/tiny_mce/tiny_mce.js" type="text/javascript"></scr' + 'ipt>\n'
    );
}, 10);

Instead.

Upvotes: 2

Andy E
Andy E

Reputation: 344675

Best not to use a string, but an anonymous function instead:

window.setTimeout(function () {
    winId.document.write(
      '<script src="../js/tiny_mce/tiny_mce.js" type="text/javascript"></script>\n'
    );
}, 10);

Using strings in setTimeout and setInterval is closely related to eval(), and should only be used in rare cases. See http://dev.opera.com/articles/view/efficient-javascript/?page=2

It might also be worth noting that document.write() will not work correctly on an already parsed document. Different browsers will give different results, most will clear the contents. The alternative is to add the script using the DOM:

window.setTimeout(function () {
    var winDoc = winId.document;
    var sEl = winDoc.createElement("script");
    sEl.src = "../js/tiny_mce/tiny_mce.js";
    winDoc.getElementsByTagName("head")[0].appendChild(sEL);
}, 10);

Upvotes: 4

Karl Johan
Karl Johan

Reputation: 4032

You have to escape the " in your script tag attributes with \" so it would read:

window.setTimeout("winId.document.write('<script src=\"../js/tiny_mce/tiny_mce.js\" type=\"text/javascript\"></script>\n')", 10);

Upvotes: 0

DisgruntledGoat
DisgruntledGoat

Reputation: 72560

It's because you're using nested double quotes. Quotes delimit strings so when you get to the second one, it thinks the string has ended, as you can see from the colour highlighting in the code you posted. You need to escape them with \":

window.setTimeout("winId.document.write('<script src=\"../js/tiny_mce/tiny_mce.js\" type=\"text/javascript\"></script>\n')", 10);

Upvotes: 1

Related Questions