Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get input from Chrome's Javascript console?

Is there a way to programmatically get input from the Javascript Console of Google Chrome, similar to readline() in Firefox?

like image 754
Daniel Duan Avatar asked Nov 28 '11 16:11

Daniel Duan


3 Answers

This is an indirect method of taking inputs:

Declare a function in JavaScript:

function your_command_here()  {
    //code
}

As Chrome's console basically provides methods for communicating with the page's contents, like JavaScript variables, functions, etc., so declaring a function as a receivable command can be an option.

In the console, for providing input, the user shall type:
your_command_here()

Another workaround is:
Declare a function:

function command(var cmnd)  {
    switch(cmnd)  {
        case "command1":
            //code
        break;
    }
}

So the user can (more conveniently) type:
command("user's command here")

like image 70
Vedaant Arya Avatar answered Nov 12 '22 12:11

Vedaant Arya


A tricky way to do this is assigning a getter to a property of a window object

Object.defineProperty(window, 'customCommand', {
  get: function() {
    console.log("hey");
    return "hey";
  }
});

So when you type "customCommand" (without parenthesis) it will print your console.log text to the console while the console is "getting" the variable.

You will still have to return something though, and I'm not sure how you could change the order so that the value is returned first and the text in the console appears second. It's definitely possible though, I've seen this happen.

like image 33
Marcin Wasilewski Avatar answered Nov 12 '22 10:11

Marcin Wasilewski


We can do is hook the console.log so whenever it logs something we can access, otherwise there is no such direct method as like in firefox which does this possible for us in a simple single line code.

var tempStore = [];
var oldLog = console.log;

console.log = function() {
    tempStore.push(arguments);
    oldLog.apply(console, arguments);
}
like image 3
sanketpatel299 Avatar answered Nov 12 '22 11:11

sanketpatel299