访问iframe之外的元素 [英] Accessing an element outside of iframe
问题描述
我有一个文件: 1.html ,里面有一个 iframe 。
我想访问一个元素(比如说myelement)存在于 iframe 中的 1.html (iframe之外)。
我该怎么做?
我尝试过:
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.html 和 http://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
在两者之间进行通信,但这仅在浏览器支持此方法且您可以控制时才有用两种资源。在MDC页面上有关于 window.postMessage
的更多详细信息: https://developer.mozilla.org/en/DOM/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. There is more detailed information about window.postMessage
on the MDC page: https://developer.mozilla.org/en/DOM/window.postMessage
编辑 - 假设两种资源来自同一个来源
在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屋!