简体   繁体   中英

How to execute script from an Input field on JS?

I want to execute script from an editable input field when clicking a button

for example, If you type " alert("x"); ", I want to alert you "x", but also if you type " for(i=0;i<3;i++){alert(i);} " I want it to execute it.

How can I achieve this?

Edit: eval() is the only solution? Because I read that it is dangerous: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/eval#section_5

Please note that you're taking input from the user and running it in the context of a script on your site. So the script can do anything that JavaScript running on your browser/domain would have the ability to do (including cookie stealing, XSS, drive-by malware, etc.).

The only thing you can realistically do to mitigate the risks is to not eval() user-provided content. I'd suggest to consider the following alternatives:

  1. Use iframe as an environment to run user's script: http://dean.edwards.name/weblog/2006/11/sandbox/
  2. Use Caja. It allows websites to safely embed DHTML web applications from third parties, and enables rich interaction between the embedding page and the embedded applications. It uses an object-capability security model to allow for a wide range of flexible security policies. http://code.google.com/p/google-caja/

Happy coding!

使用 eval() 命令,它将评估并执行您传递给它的 javascript。

使用 eval,比如 onclick="eval(document.getElementById('your_input'))"

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