Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 676
Joey Yi Zhao Avatar asked Sep 26 '17 03:09

Joey Yi Zhao


People also ask

How do I check output of console log?

Steps to Open the Console Log in Google Chrome By default, the Inspect will open the "Elements" tab in the Developer Tools. Click on the "Console" tab which is to the right of "Elements". Now you can see the Console and any output that has been written to the Console log.

What is the result of eval?

eval() returns the completion value of statementsFor if , it would be the last expression or statement evaluated. The following example uses eval() to evaluate the string str .

What does eval () do in JavaScript?

JavaScript eval() The eval() method evaluates or executes an argument. If the argument is an expression, eval() evaluates the expression. If the argument is one or more JavaScript statements, eval() executes the statements.

What is $$ eval?

$$eval() method. This method runs Array. from(document. querySelectorAll(selector)) within the page and passes the result as the first argument to the pageFunction .


1 Answers

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.

like image 191
JohnStands Avatar answered Nov 25 '22 06:11

JohnStands