How to access parent Iframe from JavaScript
Well, I have an IFrame, which calls a same domain page. My problem is that I want to access some information from this parent Iframe from this called page (from JavaScript). How can I access this Iframe?
Details: There are several Iframes just like this one, that can have the same page loaded, because I am programming a Windows environment. I intend to close this Iframe, that's why I need to know which I should close from inside him. I have an array keeping references to these Iframes.
EDIT: There iframes are generated dynamically
Also you can set name and ID to equal values
<iframe id="frame1" name="frame1" src="any.html"></iframe>
so you will be able to use next code inside child page
parent.document.getElementById(window.name);
Simply call window.frameElement
from your framed page.
If the page is not in a frame then frameElement
will be null
.
The other way (getting the window element inside a frame is less trivial) but for sake of completeness:
/**
* @param f, iframe or frame element
* @return Window object inside the given frame
* @effect will append f to document.body if f not yet part of the DOM
* @see Window.frameElement
* @usage myFrame.document = getFramedWindow(myFrame).document;
*/
function getFramedWindow(f)
{
if(f.parentNode == null)
f = document.body.appendChild(f);
var w = (f.contentWindow || f.contentDocument);
if(w && w.nodeType && w.nodeType==9)
w = (w.defaultView || w.parentWindow);
return w;
}