0

I am working on an asp.net project and on part of it, I needed to print a part of the page which contains an image using javascript. After some digging, I found a code and it works fine.

<script>


function VoucherSourcetoPrint(source) {
    return "<html><head><script>function step1(){\n" +
            "setTimeout('step2()', 10);}\n" +
            "function step2(){window.print();window.close()}" +
            "\n</scri" + "pt></head><body onload='step1()'>\n" + <%-- lokk this line--%>
            "<img src='" + source + "' style='width: 300px; height: 150px; margine:none;' /></body></html>";
}

function VoucherPrint(source) {    
    Pagelink = "about:blank";
    var pwa = window.open(Pagelink, "_new");
    pwa.document.open();
    pwa.document.write(VoucherSourcetoPrint(source));
    pwa.document.close();
}


</script>

As you can see on the first function it is returning a string and in that there is a script closing tag, which is written as </scri" + "pt>, first I thought it was a mistake and tried removing the extra quotes and plus sign and then the string showing error.

enter image description here

I am confused, why is it have to be like </scri" + "pt>??

4
  • 2
    To avoid an HTML parser from reading this JavaScript code and interpreting it as HTML. Commented Mar 27, 2019 at 11:49
  • then why script starting tag is not like that? Commented Mar 27, 2019 at 11:51
  • Because the HTML parser doesn't search for a starting script tag from within a script. Commented Mar 27, 2019 at 11:52
  • You only need to stop the closing tag from closing the <script> tag prematurely. Commented Mar 27, 2019 at 11:52

1 Answer 1

2

Because the HTML parser will find the sequence of characters "</script>" and end the script element. It will then pass invalid JavaScript to the JavaScript parser.

Here is a simplified example:

<script>console.log("</script>");</script>
▲       ▲           ▲▲        ▲  ▲
1       2           34        5  6
  1. Script element start tag.
  2. Begining of JavaScript (console.log(" - not a compilable script).
  3. End of JavaScript
  4. Script element end tag
  5. Text to show as plain text in the HTML document (");)
  6. Script end for with no matching open tag. Discarded by HTML parser as an error.

A more elegant approach is to just escape the /:

<script>console.log("<\/script>");</script>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.