execute javascript from textarea

孤街浪徒 提交于 2019-12-01 04:13:39

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);
} 

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.

Some HTML:

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

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);
}

Thnx @Prodigy && @JayC !!!

such a simple solution, I did not know such a function existed :)

using the eval() function did the trick!!!

HTML

<textarea id="cnsl"></textarea>
<button onclick="run()"> run </button>
<canvas id="canvas" width="200" height="200"></canvas>

javascript

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

function run() {    
    return eval(cnsl.value); // << did the trick ;)
}

//canvas
var ctx;

function setup() {
    var canvas = document.getElementById('canvas');
        ctx = canvas.getContext('2d');
}
setup();​

Not sure if this will work in JavaScript but it works in other languages, try importing your script into the script that has the text area then when you want to do the action in the text area call the method in the imported script that has the code you want to execute

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