Skip to main content
51 of 54
Updated demo to avoid confusion with lazy object expansion.
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 (please leave the comment intact):

<!-- console visualization; see http://meta.stackexchange.com/a/242491 -->
<script src="https://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];

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

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

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

// sample click handler
document.querySelector("button").addEventListener("click", function(e) {
  console.log("clicked: %o", this);
});

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

canon
  • 2.2k
  • 1
  • 24
  • 33