自己尝试编辑器 JS [英] Try It Yourself Editor JS

查看:31
本文介绍了自己尝试编辑器 JS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个非常简单的编辑器,效果很好.但是,我只是尝试将 JavaScript 放入其中,但无法使其正常工作.

编辑器的代码:

<input id="button" onclick="update();"type="button" value="更新页面">

<div id="tryitcontainer"><textarea id="codebox"></textarea><iframe id="showpage"></iframe>

编辑器的 JavaScript:

我只是想运行一些简单的 JavaScript,它会在单击图像时更改图像.当我在完整的浏览器中运行这段代码时,它运行良好,所以我知道是编辑器出了问题.

是否有我遗漏的简单修复方法?

解决方案

由于安全原因,通过innerHTML插入的JavaScript不会被执行:

<块引用>

HTML5 指定不应执行通过 innerHTML 插入的

还有这个:

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 it here

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆