JavaScript – Reference Browser Window by name? [duplicate]

No. Without a reference to the window, you can’t find it again, by name or otherwise. There is no collection of windows.

UPDATE: Here’s how you could do it yourself:

var windows = {};
function openWindow(url, name, features) {
    windows[name] = window.open(url, name, features);
    return windows[name];
}

Now, openWindow will always open the window, and if the window already exists, it will load the given URL in that window and return a reference to that window. Now you can also implement findWindow:

function findWindow(name) {
    return windows[name];
}

Which will return the window if it exists, or undefined.

You should also have closeWindow, so you don’t keep references to windows that you opened yourself:

function closeWindow(name) {
    var window = windows[name];
    if(window) {
        window.close();
        delete windows[name];
    }
}

If it is not possible, what is the point giving windows names?

The name is used internally by the browser to manage windows. If you call window.open with the same name, it won’t open a new window but instead load the URL into the previously opened window. There are a few more things, from MDN window.open():

If a window with the name strWindowName already exists, then strUrl is loaded into the existing window. In this case the return value of the method is the existing window and strWindowFeatures is ignored. Providing an empty string for strUrl is a way to get a reference to an open window by its name without changing the window’s location. To open a new window on every call of window.open(), use the special value _blank for strWindowName.

Leave a Comment