Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>This sounds like invalid Javascript is being generated</strong>.</p> <p>This hypothesis can be verified with inspecting the <em>actual</em> Javascript transmitted and verifying the entire result, in context, for correctness.</p> <p>That is, imagine that this invalid Javascript was generated:</p> <pre><code>alert("&lt;div class="I just broke JS" ...&gt;") </code></pre> <p><strong>To fix this, ensure the strings literals inserted into the Javascript are valid.</strong></p> <p>For instance, the above might be written (using the following code) as:</p> <pre><code>RegisterClientScriptBlock(JsEncoder.Format(@"alert(""{0}"");", theInput)) </code></pre> <p>...and it won't break because the string is escaped before. (Take a look at this output and compare: the inserted literal will be still valid Javascript, even with quotes or other characters in the <code>theInput</code>. As an added bonus, <code>&lt;/script&gt;</code> to break the code either ;-)</p> <p>This code is "free to use, modify, sell, whatever". YMMV.</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace sbcjc.sei { public class JsEncoder { static Regex EncodeLiteralRegex; // Format a bunch of literals. public static string Format (string format, params object[] items) { return string.Format(format, items.Select(item =&gt; EncodeString("" + item)).ToArray()); } // Given a string, return a string suitable for safe // use within a Javascript literal inside a &lt;script&gt; block. // This approach errs on the side of "ugly" escaping. public static string EncodeString (string value) { if (EncodeLiteralRegex == null) { // initial accept "space to ~" in ASCII then reject quotes // and some XML chars (this avoids `&lt;/script&gt;`, `&lt;![CDATA[..]]&gt;&gt;`, and XML vs HTML issues) // "/" is not allowed because it requires an escape in JSON var accepted = Enumerable.Range(32, 127 - 32) .Except(new int[] { '"', '\'', '\\', '&amp;', '&lt;', '&gt;', '/' }); // pattern matches everything but accepted EncodeLiteralRegex = new Regex("[^" + string.Join("", accepted.Select(c =&gt; @"\x" + c.ToString("x2")).ToArray()) + "]"); } return EncodeLiteralRegex.Replace(value ?? "", (match) =&gt; { var ch = (int)match.Value[0]; // only matches a character at a time return ch &lt;= 127 ? @"\x" + ch.ToString("x2") // not JSON : @"\u" + ch.ToString("x4"); }); } } } </code></pre> <p>Happy coding.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload