2

I was wondering how to run JS code posted by a user in the TextArea when he presses button without refreshing the entire page. I want to have a canvas, a TextArea and a button. When the button is pressed, it runs code from the TextArea and then paints stuff on the canvas.

I know how to put the posted code into variable string.

What I don't know is how to run code in that string.

ouflak
  • 2,458
  • 10
  • 44
  • 49
smutny1221
  • 67
  • 6

3 Answers3

2

You should be able to wrap code in eval() function. It evaluates JavaScript code represented as a string.

Example:

eval(new String("2 + 2")); // returns a String object containing "2 + 2"
eval("2 + 2");             // returns 4

In your case you will need to read code from text area and pass it to eval() it could look something like this:

eval(document.getElementById('textareaid').value);
Matas Vaitkevicius
  • 58,075
  • 31
  • 238
  • 265
0

If it is HTML just send it to a variable with a submit button and than document.write("variable").

Andrew
  • 995
  • 6
  • 10
0

The safest and simplest way to do it that I know is with node.js:

function runStr (i){
    var vm = require ('vm');
    var box = {};
    vm.createContext(box);
    vm.runInContext(`prgm = function(){return ${i};}`, box);
    return box.prgm();
}
console.log(runStr("2 + 2")); // 4
Sapphire_Brick
  • 1,560
  • 12
  • 26