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 10x10 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!
3条答案
按热度按时间gopyfrb31#
你可以创建一个脚本元素,将它的文本(或者textContent,如果HTML5和DOM 3兼容的话)设置为脚本执行,然后将它插入到文档中。最好是在执行的过程中删除元素,这样你就不会得到大量(无用的)脚本元素。
第一个
请注意,您必须创建一个新元素,因为在HTML5中,每个脚本元素都有一个相关的标志来指示它是否已被执行,并且它只能执行一次。替换内容不会重置标志,并且克隆的脚本元素保留了它从其克隆的元素的设置。
鼓励用户执行他们自己的脚本可能会破坏文档,但我想这是你的问题。:-)
另一种方法是简单地输入
eval
,它或多或少地相当于上面的代码(但代码少得多):第一次
ni65a41a2#
Thnx @Prodigy && @JayC !!!
such a simple solution, I did not know such a function existed :)
using the eval() function did the trick!!!
zpf6vheq3#
不确定此操作是否适用于JavaScript,但适用于其他语言,请尝试将脚本导入到包含文本区域的脚本中,然后当您要在文本区域中执行操作时,在包含要执行的代码的导入脚本中调用方法