最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get console.log output from eval()? - Stack Overflow

programmeradmin1浏览0评论

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?

Share Improve this question edited Sep 26, 2017 at 7:06 Venkat 2,5793 gold badges31 silver badges64 bronze badges asked Sep 26, 2017 at 3:36 Joey Yi ZhaoJoey Yi Zhao 42.5k87 gold badges350 silver badges656 bronze badges 2
  • 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
Add a comment  | 

3 Answers 3

Reset to default 16

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.

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")')
发布评论

评论列表(0)

  1. 暂无评论