5

I am using eval() to run a script from a string. Below is the code:

eval('console.log("hello")');

I will get hello from the console output. I wonder whether I can save the hello into an variable in the current context. So I am looking for something like this:

const output = eval('console.log("hello")'); // I expect the console output is returned from eval() function.

But I get an undefined response. Is there a way for me to do that?

Venkat
  • 2,549
  • 2
  • 28
  • 61
Joey Yi Zhao
  • 37,514
  • 71
  • 268
  • 523
  • Possible duplicate of [Intercept calls to console.log in Chrome](https://stackoverflow.com/questions/9216441/intercept-calls-to-console-log-in-chrome) – qxg Sep 26 '17 at 03:41
  • 1
    Well console does not return anything so why would you expect it to return something? – epascarello Sep 26 '17 at 03:48

3 Answers3

14

It is impossible because console.log() only returns undefined, however you can make a function that will return something.

Example:

console.oldLog = console.log;
console.log = function(value)
{
    console.oldLog(value);
    return value;
};

const output = eval('console.log("hello")');

Hope this will help.

JohnStands
  • 228
  • 2
  • 10
1

While the first answer works, it causes a "Maximum call stack size exceeded" error for my case. Think this might be a better solution.

const originalLog = console.log;

console.log = function (...value) {
  originalLog.apply(console, value);
  return value;
};

const response = eval(code);
0

Have you try this?

out = ''
console.log = function(val){out = out + ' ' + val}
eval('console.log("test string")')