最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to execute script from an Input field on JS? - Stack Overflow

programmeradmin0浏览0评论

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:

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/en/JavaScript/Reference/Global_Objects/eval#section_5

Share Improve this question edited Nov 7, 2011 at 20:17 ajax333221 asked Nov 7, 2011 at 19:49 ajax333221ajax333221 11.8k16 gold badges62 silver badges95 bronze badges 2
  • Remember to be very careful when doing this. Be sure you trust your users, as all kinds of malicious javascript could be entered. – Brian Ramsay Commented Nov 7, 2011 at 20:14
  • That's true, I just read something when researching about eval() developer.mozilla/en/JavaScript/Reference/Global_Objects/… – ajax333221 Commented Nov 7, 2011 at 20:16
Add a ment  | 

4 Answers 4

Reset to default 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./p/google-caja/

Happy coding!

Try this one :) http://www.w3schools./jsref/jsref_eval.asp

Use the eval() mand and it will evaluate and execute the javascript you pass to it.

use eval, like onclick="eval(document.getElementById('your_input'))"

发布评论

评论列表(0)

  1. 暂无评论