Monday, June 10, 2013

Correcting JavaScript Console Line Numbers

‹prev | My Chain | next›

Today's task may be hopeless.

Back in the day (well 90 days ago) the ICE Code Editor would produce errors with line numbers:

The problem was that the line numbers in the console did not line up with the line numbers in the code editor. The misalignment is because the browser is calculating line numbers within <script> tags, while the editor includes 4 lines of HTML tags at the top.

Since then, I have noticed that even the line numbers have disappeared from the console:

At least they disappear most of the time. Sometimes the line numbers do show up:

More often than not, the line numbers are not included and there seems to be no rhyme or reason that might explain why the numbers vary. In both the old JavaScript version and the current Dart version, the new preview is generated via a document.write() to an iframe. I toy with the idea of trying to regenerate the preview page some other way, but then I remember that performance stinks with other approaches.

Reading through the doc on dynamic HTML insertion proves both mind numbing and unhelpful. Perhaps something to digest and attempt an alternate solution another day.

For now, I hack together code in the iframe's message handler. When the ICE Code Editor sends it new content, I now intercept it before the document.write():
window.addEventListener("message", receiveMessage, false);

function receiveMessage(event) {

  // IE will hang on for some reason...

  var html =;
  var start = html.indexOf("<script>\n");
  if (start > 0) {
    var open = html.substr(0, start + 9),
        size = open.match(/\n/g).length-1;
     var pad = "";
     while (pad.length < size) pad += "\n";
     html = html.replace(
       "$&" + pad
  document.close(); = '0';
I find a lone <script>, which is what the tempates in ICE generate, count the number of lines above it, and use that number to pad the <script> tag with newlines. And that seems to do the trick:

At least in Dartium. And only in certain cases. There are still some cases in which the error originates from the document.write() rather than the generated document:

Still, this seems enough progress tonight. I am skeptical that I will be able to find enough control over console error messages to improve past this point. Hopefully this is sufficient for a book release version of the code.

Day #778

No comments:

Post a Comment