如何用JS *** 作iFrame里的Dom

如何用JS *** 作iFrame里的Dom,第1张

<body>

<iframe id="container" name="container" src="frames/index.html"></iframe>

</body>

在chrome的console里:

document.getElementById("container")

Blocked a frame with origin "null" from accessing a frame with origin "null". Protocols, domains, and ports must match.

Blocked a frame with origin "null" from accessing a frame with origin "null". Protocols, domains, and ports must match.

Blocked a frame with origin "null" from accessing a frame with origin "null". Protocols, domains, and ports must match.

<iframe id="container" name="container" src="frames/index.html">...</iframe>�6�7

document.getElementById("container").contentWindow.document

Blocked a frame with origin "null" from accessing a frame with origin "null". Protocols, domains, and ports must match.

undefined

window.frames["container"].document

Blocked a frame with origin "null" from accessing a frame with origin "null". Protocols, domains, and ports must match.

undefined

虽然是相对路径,还是出现跨域的错误。

最后找到原因了,文件之间的 *** 作是按照跨域处理的,把文件放在web容器里,127.0.0.1 去访问就好了

直接调用iframe对象的document就可以,方法和document里的一样。不过注意,如果iframe是跨越引用的,会受到限制,不能访问其中内容。也就是你不能引用百度的页面,篡改其中的内容,只能改自己网站的。

<iframe src="xxx.html" id="myiframe"></iframe>

<script>

var mydoc=document.getElementById("myiframe").document

mydoc.write("<div id='newdiv'></div>")

mydoc.getElementById("newdiv").innerText="hello"

</script>

其实iframe是一个独立的页面,与父页面是嵌套但变量独立的关系。所以iframe加载时,如果js方法不涉及 *** 作文档对象(DOM),就直接调用;如果该js方法涉及 *** 作dom,就添加window.onload事件触发函数处理,在处理函数内调用js方法


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/bake/11731714.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-18
下一篇 2023-05-18

发表评论

登录后才能评论

评论列表(0条)

保存