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

故事扮演 提交于 2020-07-08 20:47:27

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/46417440/how-to-get-console-log-output-from-eval

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!