[英]JS document.write() writes scritps into iframe's head
有人可以向我解释document.write到iframe的工作原理吗? 我有以下代码:
<html>
<body>
<iframe id="iframe"></iframe>
<script>
var code = '<scr' + 'ipt>console.log(window.frameElement.contentWindow.document.getElementById("test") );</scr' + 'ipt><div id="test"></div>';
document.getElementById('iframe').contentWindow.document.open();
document.getElementById('iframe').contentWindow.document.write(code);
document.getElementById('iframe').contentWindow.document.close();
</script>
</body>
不确定如何操作,但标签会写入iframe的head标签,并写入正文中。 如何从传递到iframe的脚本中获取div元素。 我的示例不起作用,它返回null。
不幸的是,在现实生活中,我不知道iframe的ID,而只知道div的ID。
看看我的小提琴: https : //jsfiddle.net/85bk3cr6/1/
如果iframe与父页面域位于同一域中,则可以访问。如果两者都位于同一域中,则只需访问iframe文档并在其上使用写入功能即可。
html代码:
<html>
<body>
<iframe id="iframe"></iframe>
</body>
</html>
js代码:
document.getElementById("iframe").contentWindow.document.write('\x3Cscript type="text/javascript" src="foo.js">\x3C/script>')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.