Home / Javascript: reference the parent window from a popup

Javascript: reference the parent window from a popup

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('https://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
}