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?
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?
- Possible duplicate of Intercept calls to console.log in Chrome – qxg Commented Sep 26, 2017 at 3:41
- 1 Well console does not return anything so why would you expect it to return something? – epascarello Commented Sep 26, 2017 at 3:48
3 Answers
Reset to default 16It 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.
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);
Have you try this?
out = ''
console.log = function(val){out = out + ' ' + val}
eval('console.log("test string")')