smutny1221
smutny1221

Reputation: 67

JS How to run code posted by user in a TextArea?

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.

Upvotes: 2

Views: 74

Answers (3)

Sapphire_Brick
Sapphire_Brick

Reputation: 1672

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

Upvotes: 0

Andrew
Andrew

Reputation: 995

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

Upvotes: 0

Matas Vaitkevicius
Matas Vaitkevicius

Reputation: 61401

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);

Upvotes: 2

Related Questions