It should be simple to create JavaScript intepreter in JavaScript using eval. I got this (using jQuery terminal):
term = $('#term_demo').terminal(function(command, term) {
if (command !== '') {
var result = window.eval("(" + command + ")");
if (result !== undefined) {
term.echo(String(result));
}
} else {
term.echo('');
}
}, {
greetings: 'Javascript Interpreter',
name: 'js_demo',
height: 200,
prompt: 'js> '
});
but it don’t work when I execute function foo() { ... } the foo is not defined I need to use foo = function() { ... }. eval act like executed within (function() { <code> })(). Can it be there more complicated code that will not work too?
Is it possible to create a JavaScript interpreter using simple code without use the of js.js, that will work the same as browser console?
I’ve created a bookmarklet which appends a kind of REPL in a page, designed for the major five browsers (Chrome 1+, IE 6+, Firefox 1+, Safari 3+, Opera 9+Can’t remember the exacte version).
The core component, which evaluates the code is posted below, slightly modified + annotated.
I’ve implemented the functionality in a form, which contains several controls including an input+output textarea.
Note: The code is evaluated in the global context. And such, any variables in
codewill be leaked to the global scope. For an interpreter, you could use an iframe to create a new scope (and modifyvar winin my function).