There is such code:

<script> var newWin = window.open("about:blank", "hello", "width=200,height=200"); var html = "<html><body><h1>123</h1></body><script>window.print()</script></html>"; newWin.document.write(html); </script> 

but it is interpreted incorrectly, </script> being in the html line is regarded by the browser as the closing tag of the first line, i.e. the last closing script remains without a pair, and appears on the page '; newWin.document.write(html); '; newWin.document.write(html);

task: opening a new window and calling the print dialog. for me it is very strange that the browser perceives part of the string value as html that needs to be interpreted.

maybe there are more concise ways to solve my problem?

  • one
    a bunch of options. the simplest way is to write var html = "<html><body><h1>123</h1></body><"+"script>window.print()</"+"script></html>"; - KoVadim
  • So it will be even easier: var html = "<html><body><h1>123</h1></body><script>window.print()<\/script></html>"; - Yaant
  • Tried to add a normal doctype? - Arnial

1 answer 1

According to the rules of parsing, the ending </script> tag is first located, and only then the contents of the script are parsed. Therefore, to write in a string inside a script </script> you must use string concatenation or dummy escaping.

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