将js插入iframe无法按预期工作

时间:2016-08-29 16:25:48

标签: javascript

我正在尝试在我的网页上复制jsfiddle的功能 - 用户可以在页面上提交js,它将在iframe中执行。我在jsfiddle和我的页面上运行了一些测试代码。它适用于jsfiddle,但不适用于我的页面。任何帮助表示赞赏!

我的页面呈现css和html,但js没有执行(div背景应该是蓝色):

enter image description here

以下是fiddle iframe中的html(可行):

<html><head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <meta name="robots" content="noindex, nofollow">
  <meta name="googlebot" content="noindex, nofollow">

  <script type="text/javascript" src="/js/lib/dummy.js"></script>

    <link rel="stylesheet" type="text/css" href="/css/result-light.css">

  <style type="text/css">
    .test { display:inline-flex; padding:40px; background-color:#cccccc }
  </style>

  <title></title>         
<script type="text/javascript">//<![CDATA[
window.onload=function(){
document.querySelector('.test').style.backgroundColor="rgb(21, 160, 249)"; 
}//]]>     
</script>          
</head>

<body>
  <div class="test" style="background-color: rgb(21, 160, 249);">test</div>    
</body></html>

以下是我网页的输出:

<html><head><style>
    .test { display:inline-flex; padding:40px; background-color:#cccccc }
</style><script type="text/javascript">//<![CDATA[
window.onload=function(){
document.querySelector('.test').style.backgroundColor="rgb(21, 160, 249)";
}//]]>
</script></head><body><div class="test">test</div></body></html>

将html,css和js插入iframe的代码:

$(document).ready(function() {

  var codeContainer = document.querySelector('.executedCode'); //submitted code passed as values in attributes to hidden div on the page in node/express environment
  var html = codeContainer.getAttribute('html'); 
  var css = codeContainer.getAttribute('css');
  var js = codeContainer.getAttribute('js');

  var sandbox = $('.sandboxed');
  sandbox.ready(function() {
    var htmlContainer = document.createElement('div');
    var cssContainer = document.createElement('style');
    var jsContainer = document.createElement('script');
    jsContainer.setAttribute('type', 'text/javascript');
    var head = sandbox.contents().find('head');
    var body = sandbox.contents().find('body');
    $(head).append(cssContainer);
    $(head).append(jsContainer);
    $(html).append(htmlContainer);
    $(cssContainer).append('\n\t'+css+'\n');
    $(jsContainer).text('//<![CDATA[\nwindow.onload=function(){\n'+js+'\n}//]]>\n');
    body.prepend(html);
  });

});

window.onload似乎是一个突破点:

我只是插入警报就进行了测试。这是有效的,有效的是什么。

$(jsContainer).text("alert('hi')"); //--works
$(jsContainer).text('//<![CDATA[\nalert("hi");\n//]]>\n'); //-- works
$(jsContainer).text('window.onload=function(){\nalert("hi");\n}\n'); //-- doesn't work

1 个答案:

答案 0 :(得分:1)

执行发生在$(jsContainer).text(js)行,但尚未插入html。 您只需要在$(jsContainer).text(js)之后移动body.prepend(html)行(没有onload事件)。