【发布时间】: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