Javascript: reference the parent window from a popupJavascript: 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:

Share or Bookmark

Share or Bookmark this page using the following services. You will need to have an account with the selected service in order to post links or bookmark this page.

Subscribe or Follow

Subscribe via RSS or email, or follow me on Facebook or Twitter below. The RSS icon takes you through to Feedburner where you can select the service or application to use.

Comments

blog comments powered by Disqus