简体   繁体   English

使用Ace编辑器提供的源代码的Javascript无法在iframe上运行

[英]Javascript doesn't work on iframe with source from Ace Editor

I've been creating some HTML5 interactive learning project like the one at code academy. 我一直在创建一些HTML5交互式学习项目,例如代码学院的项目。 So now I have an ace editor on my page and i want whenever user type on the editor, the result will be displayed on the iframe i have on the same page. 所以现在我的页面上有一个ace编辑器,我希望每当用户在编辑器上键入内容时,结果都将显示在同一页面上的iframe中。 I've done that so now whenever the user type html and css code the result will appear synchronous on the iframe. 我已经这样做了,所以现在每当用户键入html和CSS代码时,结果将在iframe上同步显示。 But the problem is i try to make a color filled canvas which require javascript. 但是问题是我尝试制作需要JavaScript的彩色画布。 I copy the code from canvas tutorial from w3shcool and the canvas did appear but it appears blank with no color. 我从w3shcool的canvas教程中复制了代码,并且确实出现了canvas,但是它看起来是空白的,没有颜色。 So far here's my code. 到目前为止,这是我的代码。

Here's the script i use to put the value of ace editor into iframe: 这是我用来将ace编辑器的值放入iframe的脚本:

   <script>
   var editor = ace.edit("editor");
   editor.setTheme("ace/theme/twilight");
   editor.getSession().setMode("ace/mode/html");

    editor.getSession().on('change', function(e) {
    var x = editor.getValue();
    var iFrame =  document.getElementById('myframe');
    var iFrameBody;
    if ( iFrame.contentDocument ) 
    { // FF
        iFrameBody = iFrame.contentDocument.getElementsByTagName('html')[0];
    }
    else if ( iFrame.contentWindow ) 
    { // IE
        iFrameBody = iFrame.contentWindow.document.getElementsByTagName('html')[0];
    }
        iFrameBody.innerHTML = x;
    });

$("button").click(function(){

});
   </script>

And here's my iframe tag on html: 这是我在html上的iframe代码:

 <iframe id="myframe" name="listenMsg" frameborder="0" src="">

 </iframe>

And here's the canvas script i put on the Ace editor: 这是我放在Ace编辑器中的画布脚本:

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

   <script>

   var c=document.getElementById("myCanvas");
   var ctx=c.getContext("2d");
   ctx.font="30px Arial";
   ctx.fillText("Hello World",10,50);

   </script>

  </body>
  </html>

Your help would be appreciated 您的帮助将不胜感激

Scripts are not evaluated when setting innerHTML, you eiter need to set data url with contents of the editor as a source of your iframe. 设置innerHTML时不会评估脚本,因此您需要设置带有编辑器内容的数据URL作为iframe的源。 Or find or script elements and call iFrame.contentWindow.eval(script.textContent) on each of them. 或查找或编写脚本元素,然后在每个元素上调用iFrame.contentWindow.eval(script.textContent)

Also have a look at jsbin source code at https://github.com/jsbin/jsbin 也可以在https://github.com/jsbin/jsbin上查看jsbin源代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM