Executing Javascript from inside textarea (custom JS console)

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-04 02:13:38

问题


I am interested in building a text editor in a CMS backend that allows users to write Javascript into a textarea and test it while editing.

The closest I can think of is something like.

document.head.appendChild(document.createElement('script')).src='http://site.com/file.js';

But instead of

.src='http://site.com/file.js';

I would need to fill the script element with the textarea value. Does anyone have any idea as how to handle something like this?


回答1:


I have written a simple one of these myself (doesn't work in IE) here: http://phrogz.net/tmp/simplejs.html




回答2:


Use the eval() function.

 eval(document.getElementById('wmd-input').value);

And if you're going to let users enter JavaScript into your CMS, be sure you're up to speed on cross-site scripting (XSS).




回答3:


I think you should make an ajax call to load the page. I'd recommend JQuery, which makes it very easy, and there are plenty of examples on their site.

It would look something like this:

$.get('http://site.com/file.j', function(data) {
    $('#txta').text(data);
});

Where 'txta' is the id of the textarea.

If you want to execute the script in the browser, you can use the javascript eval() function - but I would exercise extreme caution with this approach since it can lead to all sorts of security flaws, including cross-site scripting attacks.



来源:https://stackoverflow.com/questions/4875446/executing-javascript-from-inside-textarea-custom-js-console

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!