Executing Javascript from inside textarea (custom JS console)

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?

Answers:

Answer

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

Answer

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).

Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.