简体   繁体   English

从输入运行JavaScript

[英]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. 我正在尝试创建一个脚本,该脚本将运行一些JavaScript代码,用户将通过HTML输入字段输入这些代码。 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. 当用户输入他的JavaScript并按Submit时,我将输入存储为变量。 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 : 您可以使用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 您可以使用评估-http: //www.w3schools.com/jsref/jsref_eval.asp

But is this more friendly? 但这更友好吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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