Accessing an element outside of iframe

2019-01-07 11:42发布

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")

but it didn't work!!

3条回答
干净又极端
2楼-- · 2019-01-07 12:13

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

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

Edit - assuming both resources are from the same origin

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

查看更多
萌系小妹纸
3楼-- · 2019-01-07 12:25

Communication between an iframe and parent document is not possible for cross-origin resources

that is in so many ways wrong, i dont even WANT to know where to begin. Of course cross-domain requests and algorith-exchanges have a long history, it is both well documented and working now, one might start JSON-request or even simple XMLHttp-Requests via JQuery, for example, you can even load whole .js-files AND inject them into your code - injecting code in remote sources will of course need an appropriate interface; one may achieve such a thing via communication with the responsible persons, just ask them nicely and maybe they'll cooperate if your project makes sense and has its use.

To answer the question : accessing whole documents would raise the need for transferring it beforehand - i would recommend XML for that purpose because the DOM-tree and XML are nearly interchangeable. Load the tree via .get (.ajax for remote hosts), append it to this and access it just like you want ... sounds easy and if you got some experience it IS easy. If you ever read "cross-domain" and "not possible" in the same sentence again you might as well ignore the poster - there are many people out there who dont know what they're talking about ;-)

查看更多
Root(大扎)
4楼-- · 2019-01-07 12:27

Assuming that same origin policy is not a problem, you can use parent.document to access the elements, and manipulate them.

Demo here, source of outer frame here, source of iframe here.

查看更多
登录 后发表回答