简体   繁体   中英

Running JavaScript from Input

I'm attempting to create a script which will run some JavaScript code which the user will input via an HTML input field. The effect will essentially be the same as opening the dev console and pasting your code in there, but I'd like to make it more friendly for those who are unfamiliar with the dev console.

When the user inputs his JavaScript, and presses submit, I have the input stored as a variable. What I need to do is take the content of that variable, and run it inside the browser as though it's actual code. Is it possible to do that, and how would I accomplish it?

You can achieve this using eval :

var code = "alert('ok')";
eval(code);

Not that you should be very careful when doing this, since running third party code is always dangerous.

You can use eval - http://www.w3schools.com/jsref/jsref_eval.asp

But is this more friendly?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM