访问 iframe 之外的元素 [英] Accessing an element outside of iframe

查看:19
本文介绍了访问 iframe 之外的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件:1.html,里面有一个 iframe.
我想从 iframe 访问 1.html(iframe 之外)中存在的元素(比如 myelement).
我该怎么做?
我试过了:

I have a file: 1.html and an iframe inside it.
I want to access an element (lets say myelement) which exists in 1.html (outside of iframe) from the iframe.
How can I do that?
I tried:

top.getElementById("myelement")
top.document.getElementById("myelement")  
parent.getElementById("myelement")
parent.document.getElementById("myelement")

但是没有用!!

推荐答案

iframe 和父文档之间的通信对于跨源资源是不可能的.仅当 iframe 和包含页面来自相同的主机、端口和协议时才有效 - 例如http://example.com:80/1.htmlhttp://example.com:80/2.html

Communication between an iframe and parent document is not possible for cross-origin resources. It will only work if the iframe and the containing page are from the same host, port and protocol - e.g. http://example.com:80/1.html and http://example.com:80/2.html

对于跨域资源,您可以使用window.postMessage 在两者之间进行通信,但这仅在浏览器支持此方法并且您可以控制这两种资源时才有用.

For cross-origin resources, you can make use of window.postMessage to communicate between the two, but this is only useful if the browser supports this method and if you have control over both resources.

编辑 - 假设两个资源来自同一来源

在iframe中window.parent指的是父文档的全局对象,而不是文档对象本身.我相信你需要使用 parent.document.getElementById

In the iframe, window.parent refers to the global object of the parent document, not the document object itself. I believe you would need to use parent.document.getElementById

这篇关于访问 iframe 之外的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆