iframe
s (and frame
s) are their own windows, even though in the case of iframe
s they look like they're part of the main document's window. So yes, to refer to the main document's window, they'd use parent
(or window.parent
if you want to be verbose, but clear), because they are separate objects. This is partially necessary because a lot of the things in document
end up as properties on the containing window
.
If you think about it, it makes sense: The purpose of an iframe
is to embed independently-sourced content within the page. If the main page and the iframe
(s) on it shared a single window
object, they'd be sharing global context, and quite possibly conflicting with one another.
Gratuitous live example:
Parent's HTML:
<p>I'm the parent window</p>
<iframe width="500" height="500" src="http://jsbin.com/iyogir"></iframe>
Parent's JavaScript:
function foo() {
display("<code>foo</code> called!");
}
function display(msg) {
var p = document.createElement('p');
p.innerHTML = msg;
document.body.appendChild(p);
}
Child's HTML:
<p>I'm in the frame</p>
<input type='button' id='theButton' value='Click Me'>
Child's JavaScript:
window.onload = function() {
document.getElementById('theButton').onclick = function() {
var p = window.parent;
if (!p) {
display("Can't find parent window");
}
else if (typeof p.foo !== "function") {
display("Found parent window, but can't find <code>foo</code> function on it");
}
else {
display("Calling parent window's <code>foo</code> function.");
p.foo();
}
};
function display(msg) {
var p = document.createElement('p');
p.innerHTML = msg;
document.body.appendChild(p);
}
};