Skip to content
Advertisement

Eval Javascript string and store stdout

I get Js as a string and I need to execute that script and compare the output to something. I’m using eval() here but can be anything. It runs on client side in the browser.

Is there any way to do this without changing the string a?

let a = "console.log("a")";
eval(a);
let stdout = ???

Advertisement

Answer

Using:

  • bind()
  • call()

you can extend console.log so that an additonal, separate live record is kept of all the log entries.

In the working example below, you can see that every time something is logged to the console, it is simultaneously added to the console.stdout array.


Working Example:

console.stdout = [];
console.logInclStdout = console.log.bind(console);

console.log = (logEntry) => {
    console.stdout.push(logEntry);
    console.logInclStdout.call(console, logEntry);
}


let a = "console.log('a')";
let b = "console.log('b')";
let c = "console.log('c')";

let saferFasterEval = (input) => Function(`"use strict"; ${input}`)();

saferFasterEval(a);
saferFasterEval(b);
saferFasterEval(c);

// When you want to see what has been logged via console.log
console.info(console.stdout);
Advertisement