Zhao Yi Zhao Yi - 21 days ago 9
Javascript Question

How to get console.log output from eval()?

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?

Answer Source

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.