Search code examples
javascriptdynamicashxdocument.write

document.write in StringBuilder?


I am using a StringBuilder in an ashx file to return javascript. It all works fine, except for one line...

javascript.Append("document.write(\"<script id=__ie_onload defer \" + \"src=javascript:void(0)><\/script>\");");

For readability, here is the unescaped version:

document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");

If I comment out this line, my ashx file works like a charm! If I keep it in, though, it won't even run. Is there some sort of restriction on using a document.write statement in a StringBuilder? Alternatively, is there a better way to write out Javascript from within .NET? It has to be from .NET due to the need for using server variables.


Solution

  • You have an unrecognized escape sequence in your closing script tag. \/ is not a valid escape sequence. You probably want:

    javascript.Append("document.write(\"<script id=__ie_onload defer \" + \"src=javascript:void(0)></script>\");");
    

    Or if you really want that \/ sequence, then doubly-escape the \:

    javascript.Append("document.write(\"<script id=__ie_onload defer \" + \"src=javascript:void(0)><\\/script>\");");
    

    As a debugging tip, if your tools provide you with such poor feedback that you can't even see compilation errors, try creating a test application containing the problematic code. I copied your code into a console application, something like:

    static void Main(string[] args)
    {
        var javascript = new StringBuilder();
        javascript.Append(...
        Console.Write(javascript);
    }
    

    ...and I saw the problem immediately on compilation:

    Unrecognized escape sequence

    ...with the problem sequence underlined.