In rare cases, could also be used for Selenium/WebDriver, if you’re not using their built in window handling APIs.
//get handle to some existing window
var someWinHdl = window.open(null,”some existing window name if you know it”);
//get handle to self (current window)
var selfWinHdl = window.open(null,window.name);
granted getting the current window handle this way isn’t all that useful though since you could also just use “window.self”. But it is useful to gain access to an existing window if you know it’s “window.name” value.
This same technique can also be applied for opening new windows to keep a handle on the newly opened window, just provide a real URL instead of null to window.open().
With this window handle in place you could access it like any window object such as closing it, using the stored handle variable example above:
NOTE – update 7/8/14:
For this technique, the code will only work under these conditions:
- window.name needs to be defined with a value (in the case of getting handle to self/current window) or the window name to another window (opened by current window) needs to be a valid defined window name, otherwise, it will just open a blank window and you won’t get a reference to the (correct) window handle. For current window or self, you can arbitrarily set the window.name value (e.g. to “testing123”) if it is undefined, and then you will be able to use the code above. For other windows currently open, we assume those windows were opened with a defined window.name (or that it is defined at some point) so that you can reference it. If the name is undefined (anonymous), then this code won’t work against other windows that were previously opened by the current window.
- The code here is generally not that helpful in regards to windows already opened since you get the window handle when opening the window with window.open() and storing the return value. However, sometimes one might not have stored that value in the original window.open() call, or for testing purposes, you don’t have that handle but you do have the window name. As such, you can make a repeat call with the presented code to retrieve the window handle without changing the current location/URL of that window (e.g. don’t cause it to navigate away or page refresh).