自己尝试编辑器 JS [英] Try It Yourself Editor JS
问题描述
我创建了一个非常简单的编辑器,效果很好.但是,我只是尝试将 JavaScript 放入其中,但无法使其正常工作.
编辑器的代码:
<div id="tryitcontainer"><textarea id="codebox"></textarea><iframe id="showpage"></iframe>
编辑器的 JavaScript:
我只是想运行一些简单的 JavaScript,它会在单击图像时更改图像.当我在完整的浏览器中运行这段代码时,它运行良好,所以我知道是编辑器出了问题.
是否有我遗漏的简单修复方法?
由于安全原因,通过innerHTML
插入的JavaScript不会被执行:
HTML5 指定不应执行通过 innerHTML 插入的 标签.
来自 MDN:Element.innerHTML - 安全注意事项,另见:W3:应用innerHTML 算法.
使用 jQuery 方法的可能解决方案 .append()
解决这个问题,因为它以某种方式评估内容.但这仍然不能解决您的问题,因为 JavaScript 代码是在当前范围内执行的.这是一个测试场景:
函数更新(){var codeinput = document.getElementById('codebox').value;$(window.frames[0].document.body).append(codeinput);}
尝试插入此脚本:
还有这个:
Test
<脚本>window.frames[0].document.getElementById('test').innerHTML = '更新';
第一个将返回一个 [object HTMLDivElement]
或类似的.在这里您可以看到,您仍然在与父框架相同的范围内.第二个将正确更新 iframe 中的内容.在尝试这些东西时,请记住这一点.
也许 执行插入 .innerHTML 的元素 为您提供了更多信息.
I have created a very simple editor that has been working great. However, I just tried to put JavaScript into it and I can't get it to work.
The code for the editor:
<div id="buttoncontainer">
<input id="button" onclick="update();" type="button" value="Update page">
</div>
<div id="tryitcontainer">
<textarea id="codebox"></textarea>
<iframe id="showpage"></iframe>
</div>
The JavaScript for the editor:
<script>
function update() {
var codeinput = document.getElementById('codebox').value;
window.frames[0].document.body.innerHTML = codeinput;
}
</script>
I just wanted to run some simple JavaScript that changes an image when it is clicked. This code works fine when I run it in a full browser, so I know its the editor thats the problem.
Is there a simple fix for this that I'm missing?
JavaScript inserted via innerHTML
will not be executed due to security reasons:
HTML5 specifies that a
<script>
tag inserted via innerHTML should not execute.
from MDN: Element.innerHTML - Security considerations, see also: W3: The applied innerHTML algorithm.
A possible solution using the jQuery method .append()
works around that, as it somehow evals the content. But this will still not solve your problem, as the JavaScript code is executed in the current scope.
Here's a test scenario:
function update() {
var codeinput = document.getElementById('codebox').value;
$(window.frames[0].document.body).append(codeinput);
}
Try to insert this script:
<script>
alert( document.getElementById('tryitcontainer') );
</script>
and this one:
<p id="test">Test</p>
<script>
window.frames[0].document.getElementById('test').innerHTML = 'updated';
</script>
The first one will return a [object HTMLDivElement]
or similar. Here you can see, that you're still in the same scope as the parent frame. The second one will correctly update the content within the iframe. Keep that in mind, when experimenting with those things.
Maybe Executing elements inserted with .innerHTML has some more infos for you.
这篇关于自己尝试编辑器 JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!