Skip to content
Advertisement

execute javascript from textarea

I’m not entirely sure if this is possible, but I’m trying to create a mini faux editor in a browser that runs javascript on the page. Here’s what I’ve been trying to do in theory

HTML

​<textarea id="cnsl"></textarea>
<button onclick="run()"> run </button>

javascript

var cnsl = document.getElementById('cnsl');

function run() {
    return cnsl.value
}

more specifically I’m trying to write to a canvas element via the ‘code’ I type into the text area, so that if, for example, i type ctx.fillRect(10,10,10,10); into my textarea and then execute that run() function the 10×10 square will appear in my canvas.

I had a little luck when instead of returning the cnsl.value I wrote it to the innerHTML of an empty script element in my HTML. But this would only work the first time I’d execute the function and then won’t work again until I refresh the page. (for example this: http://jsfiddle.net/ur5KC/1/ which doesn’t seem to work on jsfiddle but works locally as I described above)

…any ideas??? thnx in advance!

Advertisement

Answer

You can create a script element, set its text (or textContent if HTML5 and DOM 3 compatible) to the script to execute, then insert it in the document. Best to remove elements as you go so you don’t end up with a large number of (useless) script elements.

function run() {
    var el = document.getElementById('cnsl');
    var scriptText = el.value;
    var oldScript = document.getElementById('scriptContainer');
    var newScript;

    if (oldScript) {
      oldScript.parentNode.removeChild(oldScript);
    }

    newScript = document.createElement('script');
    newScript.id = 'scriptContainer';
    newScript.text = el.value;
    document.body.appendChild(newScript);
}
<textarea id="cnsl"></textarea>
<button onclick="run();">run</button>

Note that you must create a new element because in HTML5, each script element has an associated flag to indicate whether it’s been executed and it can only be executed once. Replacing the content doesn’t reset the flag, and a cloned script element keeps the setting of the element it was cloned from.

Encouraging a user to execute their own scripts may destroy the document, but that’s your problem I guess. 🙂

An alternative is to simply eval whatever they enter, it’s more or less equivalent to the above (but a lot less code):

function run() {
  var el = document.getElementById('cnsl');
  el && eval(el.value);
}
<textarea id="cnsl"></textarea>
<button onclick="run();">run</button>
Advertisement