Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing an element outside of 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") 

but it didn't work!!

like image 940
user646093 Avatar asked Apr 09 '11 11:04

user646093


2 Answers

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.

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

like image 159
Gary Chambers Avatar answered Sep 22 '22 23:09

Gary Chambers


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.

like image 33
Salman A Avatar answered Sep 24 '22 23:09

Salman A