简体   繁体   English

如何从 JS 上的输入字段执行脚本?

[英]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.例如,如果您输入“ alert("x"); ”,我想提醒您“x”,但如果您输入“ for(i=0;i<3;i++){alert(i);} “我希望它执行它。

How can I achieve this?我怎样才能做到这一点?

Edit: eval() is the only solution?编辑: eval() 是唯一的解决方案? Because I read that it is dangerous: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/eval#section_5因为我读到它很危险: 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.).因此,脚本可以执行在您的浏览器/域上运行的 JavaScript 能够执行的任何操作(包括 cookie 窃取、XSS、路过式恶意软件等)。

The only thing you can realistically do to mitigate the risks is to not eval() user-provided content.为了降低风险,您实际可以做的唯一一件事就是不要 eval() 用户提供的内容。 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/使用iframe作为运行用户脚本的环境: 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.它允许网站安全地嵌入来自第三方的 DHTML Web 应用程序,并实现嵌入页面和嵌入应用程序之间的丰富交互。 It uses an object-capability security model to allow for a wide range of flexible security policies.它使用对象能力安全模型来支持各种灵活的安全策略。 http://code.google.com/p/google-caja/ http://code.google.com/p/google-caja/

Happy coding!快乐编码!

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

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

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

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