1

How do I execute JavaScript I get from the user via a text field, inside the console and get the browser's console's output directly with JavaScript and/or jQuery?

user229044
  • 232,980
  • 40
  • 330
  • 338
Sazid
  • 2,747
  • 1
  • 22
  • 34

1 Answers1

5

You can use eval for that :

 console.log(eval('('+$('#yourInput').val()+')'))

Demonstration

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • You shouldn't use `eval` anywhere! It is considered as evil! Here, look at this - https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/eval – akash4eva May 07 '13 at 10:44
  • Ok, but what does the eval() function is doing here? I also heard its evil-ness. – Sazid May 07 '13 at 10:45
  • eval evaluates/performs the JavaScript expressions/statements passed as argument to it. See https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/eval – Ali May 07 '13 at 10:47
  • 5
    @akash4eva Stop propagating irrational fears. `eval` is perfectly suited to this situation. – Denys Séguret May 07 '13 at 10:49
  • 2
    `eval` is fine. It becomes evil when you take user input data into your application with `eval`. But evaluating user code with `eval` is totally fine. – elclanrs May 07 '13 at 10:49
  • 2
    Solid answer +1 op might also find this useful http://stackoverflow.com/questions/15409639/how-to-execute-different-partsof-the-js-code-in-one-scope/15409716#15409716 – Benjamin Gruenbaum May 07 '13 at 11:00
  • But, what about getting the output from the console? Please someone tell me! – Sazid May 07 '13 at 12:24
  • You mean you want to eval what the user types in the console ? [There's no function for that](https://developer.mozilla.org/en-US/docs/DOM/console). – Denys Séguret May 07 '13 at 12:56