-9

I'm trying to figure out how to capture stderr and stdout in the browser from the currently executing javascript.

This will be for a live code editor.

chovy
  • 72,281
  • 52
  • 227
  • 295

2 Answers2

4

JS has no stdout or stderr - it just has the console.

It is possible to override console.log() with your own function that does whatever processing you want, and ideally then pass the log message to the original console.log function. Ditto for console.error.

For example:

(function() {
    const log_orig = console.log;

    console.log = function() {
        log_orig.call(console, 'log called with ' arguments.length + ' parameters');
        log_orig.apply(console, arguments);
    }
})();  // IIFE
Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • What about errors? – chovy Dec 06 '21 at 11:21
  • 1
    @chovy errors are typically reported using `console.error`, so you'd duplicate the above code with `log` replaced by `error`. – Alnitak Dec 06 '21 at 11:22
  • even like if the code doesn't compile? I know if they specificaly call `console.error` i can get it. – chovy Dec 06 '21 at 11:52
  • that's a different problem that wasn't in your original question - ISTR you can trap `window.onerror` on some browsers to catch JS interpreter errors – Alnitak Dec 06 '21 at 11:54
  • see e.g. this old link - https://danlimerick.wordpress.com/2014/01/18/how-to-catch-javascript-errors-with-window-onerror-even-on-chrome-and-firefox/ – Alnitak Dec 06 '21 at 12:03
2

You can't.

Any output and errors that browser outputs are not exposed to JS.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335