-3

I am attempting to create a console. Let's say I a function foo() and I enter it into the "console". The console should run that function. I attempted the following:

var $console = $('.console');
var console = {
 log: function(txt) {
  $console.append(txt + '<br>');
 },
 clear: function() {
  $console.text(' ');
 }
}
function foo() {
  console.log('foo ran');
}
var bKeys = [];
$('body').keydown(function(event) {
 if (event.which === 13) {
  //run the provided function from the input
    ($('.run').text())();
 }
});
.console {
 position: absolute;
 right: 0px;
 top: 0px;
 background-color: #fff;
 width: 300px;
 height: 100%;
 box-shadow: 0px 0px 5px #444;
 overflow-y: auto;
}
.run {
 position: fixed;
 bottom: 0px;
 width: 295px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='console'><input class='run' type='text' placeholder='Run a command...'/>Console: <br> </div>

What I tried was returning the text and trying to run that function after Enter is pressed in the <input>. However, that isn't working. How can I run a typed function from <input>?

Rojo
  • 2,749
  • 1
  • 13
  • 34
  • 2
    OK, what is the question – nbokmans Mar 13 '19 at 13:27
  • @nbokmans I'm trying to run a function from the console that I'm making through ``, but I have no idea how do that. So, how do I do that? – Rojo Mar 13 '19 at 13:28
  • You _could_ (read: **[don't](https://stackoverflow.com/questions/86513/why-is-using-the-javascript-eval-function-a-bad-idea)**) use `eval()` - But, why would you do this? – Lewis Mar 13 '19 at 13:37
  • @Lewis I'm using codepen and there's no console. Also, I'm coding at school and I can't open the Google Chrome's console. – Rojo Mar 13 '19 at 16:29

1 Answers1

1

If you're trying to create a new debugger panel like every browser have built-in, you need a lot of things. If you want to allow running really any JS code, you might use eval(userInputText). This may be dangerous if you don't validate userInputText and don't handle errors.

But if you just want to allow calling predefined commands from a fixed list, and here is an idea to start:

  • Add an event handler to the input to detect when its content changes.
  • Read out the content, this will be the key, the command's name.
  • Create an object/array/dictionary of allowed/possible commands. The key/index should be the command's name, the value is a function.
  • When the input changes, validate it, then run something like commandStorage[userInputText]().
  • You can extend this to pass parameters, add complex calls, anything.
klenium
  • 2,468
  • 2
  • 24
  • 47