Dexter  Goodwin

Dexter Goodwin


How does MDN Intercept `console.log`?

DevLog 003

In the last post we looked at:

  • Uploading from WebStorm to GitHub
  • Semantic Versioning
  • Conventional Commits

In this post, we want to resume developing our code editor. The basic objective is to create a box that the user can enter some code and, with the touch of a button, can see the result of their code.

First Iteration Behaviour

The first implementation was design around the eval function, the result of which would be displayed in the result pane. Putting in a string “hello” would result in hello being displayed. Additionally, assigning a variable and then putting that variable alone on the last line, the result pane displays the value of the variable.

Instead, it would be more intuitive to use console.log instead, which is what MDN has done in their interactive examples.

Background for the Second Iteration

In NodeJS, it’s possible to read the process.stdout stream, or create a new logger with custom streams. So, I looked for resources on how to hook the output of the browser’s console.log. From what I could understand, there is no way to get the output of console statements in the browser.

However, it is possible to intercept the arguments of console.log when called. A StackOverflow answer has a solution. By reassigning the original console.log statement to a new variable, we can assign our own custom function to console.log. Note that this doesn’t intercept the output of log statements, but only intercepts the arguments.

#console-log #typescript #react #javascript

How does MDN Intercept `console.log`?