views:

100

answers:

3

I'm opening new page using JS and writing into it the HTML code, however when I try to write JS inside the new page using document.write() function it doesn't work. Apparently the main JS closes as soon as the it sees /script> which is intended for the JS of the new page that will be opened.

Is there away around this?

var opened = window.open("");
opened.document.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;");
opened.document.write("<html lang=\"en-US\" xml:lang=\"en-US\" xmlns=\"http://www.w3.org/1999/xhtml\"&gt;");
opened.document.write("<head><title>Print Copy</title></head>");
opened.document.write("<body>");
opened.document.write("<script type=\"text/javascript\">");
opened.document.write("</script>");
opened.document.write("<p>test</p></body></html>");
A: 

EDIT: as others pointed out, you should escape the slash with a backslash.

The easy (but non standard) solution is to break your string:

opened.document.write("</scr"+"ipt>");
Jerome
This approach depends on browsers performing error recovery and should be avoided. It is invalid HTML. http://bit.ly/5dN2dv
David Dorward
I didn't know that, you learn something new everyday :) The FAQ you linked to is interesting.
Jerome
+7  A: 

This sounds like you are embedding the JS into an HTML document rather than using an external file, and that you are serving it as text/html. (If it was XHTML then you would get a simple well-formedness error).

You could move the code to an external file (which is the simplest option), or you can escape the slash characters on anything that looks like an end tag:

document.write("<\/script>");

Note you should do this to all end tags (not just </script>) due to the way SGML works (even if most browsers don't completely respect the rules of SGML).

There is a good FAQ entry on this subject.

David Dorward
Have you seen this yet: http://stackoverflow.com/questions/1985385/script-inside-javascript-code-document-write ? Moving the script to an external file may cause IE to hang with *document.write*? Curious...
Crescent Fresh
+5  A: 

If you do not fancy splitting the string, you can also use the escape charachter:

opened.document.write("<\/script>");
Daniel Vassallo