April 26, 2000 - open() Method's Return Value | WebReference

April 26, 2000 - open() Method's Return Value

Yehuda Shiran April 26, 2000
open() Method's Return Value
Tips: April 2000

Yehuda Shiran, Ph.D.
Doc JavaScript

To handle references to a window properly, you should always assign the result of a window.open() call to a variable. A call to the window.open() method returns a value of the new window's object if the window opens successfully, or null if it fails (due to low memory, for example). This value is vitally important if your script needs to address elements of that new window. After the new window is open, however, no parent-child relationship exists between the windows. Take a look at the following statement:

var recentTips = window.open("https://www.docjs.com/tips/", "tips");

Here we are assigning the new window's window object to a variable named recentTips. If you are invoking the window.open() method inside a function, be sure to omit the var keyword, because the variable should be global. Otherwise, the window's reference is located in a local variable, and cannot be accessed after the function's execution ends. The following statement displays the URL of the new window in an alert dialog box:

alert(recentTips.location.href);

You can also change the URL of the new window via its reference:

recentTips.location.href = "https://www.usatoday.com/";

By specifying a TARGET attribute or assigning a value to the window object's name property we are able to name a window. But how can we reference an existing window by its HTML name? The answer is simple. If you invoke the window.open() method with an empty string ("") for the URL, and the name of the existing window, a reference of the window is returned (without loading anything into the window). Take a look at the following link:

<A HREF="https://www.cnet.com/" TARGET="news">CNET</A>

When we invoke the following statement, we get a reference to the new window:

var latestNews = window.open("", "news");

If you just want to change the URL of an existing window, you can also invoke the window.open() method directly with the URL of the desired page:

function changeURL(winName, newURL) {
  win = window.open(newURL, winName);
}

Learn more about opening windows in Tutorial 1, Working with Windows.