1

Is there a way in JavaScript in browsers, to run an other script stored as string independently from the main JavaScript and also get the console output from that script in a way that it is not (just) printed to the console?

Basically I want something like this:

var script = 'console.log("Hello World");'

var consoleOut = script.runAsJS();
user11914177
  • 885
  • 11
  • 33

3 Answers3

3

What environment?

In browser, you can use web workers.

In Node/Deno you can use VM or spawn separate process.

gkucmierz
  • 1,055
  • 1
  • 9
  • 26
0

Maybe you could look into eval()

Hopefully this is what you mean by 'independent from the main javascript'. If you mean as in variables from the outer scope will not be defined in the string, eval() will not work for you. It is treated as part of the same program.

Edit: also see this answer on specifying the scope of eval()

If you want to store the console.log in a variable, try something like this:

var script = 'console.log("Hello World");'
var consoleOut = [];
script = script.replace(/console\.log/g,"consoleOut.push");
eval(script);

Edit: as suggested by comments, eval is often not the best in terms of security. A more efficient and secure option may be Function, however the docs mention that Function still suffers from security issues:

var script = 'console.log("Hello World");'
var consoleOut = [];
scriptFunction = new Function(script.replace(/console\.log/g,"consoleOut.push"));
scriptFunction();

Leaf the Legend
  • 471
  • 3
  • 9
0

To run an other script stored as string you can use eval() as suggested by answer from @Leaf the Legend. And for script to run independently from the main JavaScript you can use IIFE.

So combining eval and IIFE you may get your desired result. Like (function() { eval(script) })();

Below is small snippet which may elaborate better.

// variable from global scope.
let a = 10;

function runAsJS(script) {
  (function() {
    eval(script)
  })();
}

let script = `
  let a = 10; 
  a += 10;
  console.log('a from eval script', a);`;

runAsJS(script);
console.log('a from global scope', a);
Karan
  • 12,059
  • 3
  • 24
  • 40
  • Well that just is Leaf the Legends answer – user11914177 Jul 07 '20 at 10:14
  • No, for `eval` yes, but I have suggest to use `IIFE` which can make difference and variable defined inside `script` will have limited scope to itself only. It will not affect global variables. – Karan Jul 07 '20 at 10:16