【问题标题】:Why is my script pushed in a iframe is executed in the parent?为什么我在 iframe 中推送的脚本在父级中执行?
【发布时间】:2019-09-07 17:00:40
【问题描述】:

我尝试将脚本推送到 iframe 中。 至少脚本被推送到“某处”,因为它在控制台中输出了一些东西。 如果我在调试器中打开 iframe,我会在 iframe 内部的文档中看到它。 所以到目前为止一切看起来都很好。

但是当它运行时消息与执行的地方不一致。 它的输出看起来像是在父级内部运行的:它找到了一个仅存在于父级中的#parent,而没有找到已在子级中推送的#child。

抱歉,由于安全问题(父级和 iframe 之间的通信),我无法制作小提琴

<html>
<body>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<div id='parent'>
<iframe id="frame"></iframe>
  <script>
  var $frm = $("#frame");
  var $doc = $frm[0].contentWindow ? $frm[0].contentWindow.document : $frm[0].contentDocument;
  var $body = $($doc.body);
  $body.html(''); 
  $body.append("<div id='child' >this isthe child</div>");  
  var $head = $($doc.head);
  $head.append($("<script"+">console.log('location = '+window.location + ' ' + 'isParent:' + $('#parent').length + ' ischild:' + $('#child').length); <\/"+"script>"));  
  </script>
</body>
</html>

这个输出

location = file:///tmp/test.html isParent:1 ischild:0

我期待

location = about:/blank isParent:0 ischild:1

【问题讨论】:

    标签: javascript jquery iframe


    【解决方案1】:

    这是因为 jQuery 处理评估 append 中的脚本内容,而不是让浏览器来处理。这样做是因为当您通过innerHTMLinsertAdjacentHTML 插入脚本时,不会执行该脚本。 jQuery 确保脚本执行,不管它如何实现append

    如果您直接使用 DOM 附加脚本,它会在正确的文档中执行(并且由于 $ 未定义而失败)。

    为此,请替换:

    $head.append($("<script"+">console.log('location = '+window.location + ' ' + 'isParent:' + $('#parent').length + ' ischild:' + $('#child').length); <\/"+"script>"));  
    

    var script = document.createElement("script");
    script.textContent = "console.log('location = '+window.location + ' ' + 'isParent:' + $('#parent').length + ' ischild:' + $('#child').length);";
    $head[0].appendChild(script);
    

    当然,您可能希望将 jQuery 添加到 iframe 的文档中,以便定义 $。 :-) 你可以使用script 上的load 事件来做到这一点:

    var script = document.createElement("script");
    script.onload = function() {
        script = document.createElement("script");
        script.textContent = "console.log('location = '+window.location + ' ' + 'isParent:' + $('#parent').length + ' ischild:' + $('#child').length);";
        $head[0].appendChild(script);
    };
    script.src = "https://code.jquery.com/jquery-1.12.4.min.js";
    $head[0].appendChild(script);
    

    通过这些更改,您将获得预期的结果:

    location = about:blank isParent:0 ischild:1

    【讨论】:

    • 事实上我正在做一个 .append($("
    猜你喜欢
    • 2014-07-25
    • 1970-01-01
    • 2013-09-13
    • 1970-01-01
    • 2017-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多