Home > front end >  How do I run javascript code from a HTML input box?
How do I run javascript code from a HTML input box?

Time:12-10

I am currently trying to run JavaScript code from a HTML input box for my online code compiler project.

function runCode(){
     let code = document.getElementById('code').value
     console.log(code)
}

I was expecting it to actually run the code instead of just logging it as a string

CodePudding user response:

This is good if you're just playing around and having fun learning JavaScript and whatnot. This is not something you just want to put out on the web if you aren't that experienced. If you do decide to put it on the web, make sure not to save anybody's code into a database. You don't want UserA to write code which may execute on UserB's computer. Given your experience level, I'd just say "don't do it". Without further ado:

const userInput = 'console.log("Hello World");';

// method 1 
eval(userInput);

// method 2
new Function(userInput)()

If you want to allow experimental javascript features and other new JS features, you will need to use babel standalone to transform the code first. Something like this:

<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
const userInput = 'console.log("Hello World");';
var output = Babel.transform(userInput, { presets: ["env"] }).code;

eval(output);
new Function(output)();

CodePudding user response:

Use eval()

run.onclick =() => {
  eval(editor.value)
}
<textArea id="editor">console.log('test')</textArea>
<button id="run">run</button>

  • Related