Javascript: reference the parent window from a popup
Posted November 4th, 2009 in Javascript
If a window has been opened with the Javascript window.open function, that window can be referenced using window.opener. This post shows some examples about how to do this.
window.opener
The window.opener property will only be set if the window is a popup window, opened like in the following example:
window.open('http://www.electrictoolbox.com/', '', 'width=900,height=600,resizable,scrollbars')
The DOM and all the functions from the parent window are then accessible from the popup/child window via window.opener.
For example, if the parent window contained a function called "foo", it could be called from the popup window like so:
window.opener.foo();
Testing if the parent window exists, and is still open
If a property, method etc is accessed using window.opener and it is not a popup window, then a Javascript error will occur and other scripts on the page may no longer run. To test if the opener exists (and therefore whether this is a popup window) test for window.opener first:
if(window.opener) {
// do something
}
Even better, it's also possible to test if the parent window is still open as well:
if(window.opener && !window.opener.closed) {
// do something
}
Related posts:
- Write content into a dynamic Javascript popup (Thursday, July 1st 2010)
- Post a form to a popup window with Javascript and jQuery (Friday, November 20th 2009)
- Opening a new window with Javascript (Saturday, November 22nd 2008)
- How to check if a Javascript function exists (Saturday, July 5th 2008)
- Testing if a Javascript variable is defined (Tuesday, October 23rd 2007)

Comments
blog comments powered by Disqus