NeilFraser / JS-Interpreter

A sandboxed JavaScript interpreter in JavaScript.
Apache License 2.0
1.98k stars 355 forks source link

ReferenceError: console is not defined #224

Closed venkateshatgit closed 2 years ago

venkateshatgit commented 2 years ago

Interpreter gives error for console.log() console.log(6); Uncaught ReferenceError: console is not defined

I would love to contribute in solving this issue.

NeilFraser commented 2 years ago

The console is not part of the JavaScript spec, so it doesn't exist in the interpreter. You can create a console API using this code:

    var myCode = 'console.log("Hello world");';
    var initFunc = function(interpreter, globalObject) {
      // Create 'console' global object.
      var pseudoConsole = interpreter.nativeToPseudo({});
      interpreter.setProperty(globalObject, 'console', pseudoConsole);

      // Define 'console.log' function.
      var wrapper = function log(value) {
        return console.log(value);
      };
      interpreter.setProperty(pseudoConsole, 'log',
          interpreter.createNativeFunction(wrapper));
    };
    var myInterpreter = new Interpreter(myCode, initFunc);
    myInterpreter.run();