Skip to main content
45 of 54
added 94 characters in body
canon
  • 2.2k
  • 1
  • 24
  • 33

A duplicate of this question came up on meta.SO where I suggested a solution, copied here:


I whole-heartedly agree. If the point of these snippets is to enable us to demo functionality and display its output inline, the output pane needs to be adapted to (optionally) mirror logged messages.

Why should we bother avoiding document.write() and alert()?

  • Both assume a browser environment even if we're demonstrating a purely javascript concept. We certainly don't want either method in the middle of what should be a node.js function.
  • Neither are what we're using to debug (I hope)
  • alert() is extremely intrusive.
  • document.write() shouldn't even be suggested to the novice user without a littany of caveats
  • Neither method offers robust serialization... forget serializing objects.
  • Our debugging messages deserve more love than that from our demo tool. We can do much, much better.

My Temporary Solution

I've created a small script to include via the html snippet1:

<!-- results pane console output; see http://meta.stackexchange.com/a/242491 -->
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

1 If we ever get integrated console visualization, we can just remove this script wholesale and it should be very low-impact.

Notes:

  • All calls to console.log() (info(), warn(), error(), and clear()) are passed along to the actual console
  • Loosely imitates Chrome's output (colors and styles excluded)
  • Objects are printed using a variation of JSON.stringify() (including functions, regex, undefined, etc) with custom handling for HTMLElement
  • Works by injecting elements into the page... so, it obviously pollutes the DOM.
  • The number of entries is limited to 50. Older entries will be removed to make room for newer entries.
  • Logs unhandled errors.
  • Handles circular references. You could log window; though, I wouldn't recommend it.

Here's a demo:

// sample values
var values = [1e100, "a", true, new Date(), x => 1, /(?:)/ig, undefined, null];

// log whole array
console.log("whole array: %o", values);

// add a circular reference
values.push(values);

// log whole array 
console.log("array with circular reference: %o", values);

// remove circular reference
values.pop();

// log each value individually
values.forEach((v, i) => console.log("%i: %o", i, v));

// throw a test error
throw new Error("test!");
<!-- results pane console output; see http://meta.stackexchange.com/a/242491 -->
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

- Minified version available here: https://gh-canon.github.io/stack-snippet-console/console.min.js
- Unminified version available here: https://github.com/gh-canon/stack-snippet-console/blob/master/console.js

canon
  • 2.2k
  • 1
  • 24
  • 33