Reputation: 955
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();
Upvotes: 1
Views: 376
Reputation: 481
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();
Upvotes: 0
Reputation: 12629
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);
Upvotes: 0
Reputation: 1145
What environment?
In browser, you can use web workers.
In Node/Deno you can use VM or spawn separate process.
Upvotes: 3