【问题标题】:JS document.write() writes scritps into iframe's headJS document.write() 将脚本写入 iframe 头部
【发布时间】:2019-06-10 15:41:22
【问题描述】:

有人可以解释一下 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 的头部标签,并被写入正文。 如何从传递给 iframe 的脚本中获取 div 元素。我的示例不起作用,它返回 null。

不幸的是,在现实生活中我不知道 iframe 的 id 我只知道 div 的 id。

【问题讨论】:

  • 要在iframe中插入js代码吗?还是我错了?
  • 那么代码是错误的,因为您尝试在添加元素之前读取它......但是如果代码在 iframe 中,那么它将在当前页面的上下文中,所以选择iframe 没有意义。
  • @epascarello 天哪,你是对的,这太明显了,我没看到。创建 div 必须在代码 var 内的脚本标记之前。谢谢!

标签: javascript iframe document.write


【解决方案1】:

看我的小提琴: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>')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-14
    • 2011-02-09
    • 2015-12-20
    • 1970-01-01
    • 1970-01-01
    • 2019-05-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多