开发者

How to tell if a window exists in Javascript?

I've seen ways of seeing if a window a particular script opened is still opened, but what if it didn't?

I have a small window that has a button to click to load the large window. When I close the large one, I want a particular onUnload or onBeforeUnload to fire iff the small one is closed; if it's still open, those procedures will not fire. I may be having simply a massive brain fart but I c开发者_开发问答an't figure out how to check if the other window is open. The big one isn't opening it, so I can't simply record the handle from opening it.

In shorter terms: If window A opened window B, how can I check within window B if window A still exists?


if(window.opener && !window.opener.closed)
    alert('Yup, still there.');


window.closed will be set to true if you popped a window and it was closed (by script or user).

var win = window.open('...')';
if (win.closed)

Your case seems to be the following:

From a popup window, you can check if the window that opened it is still open using window.opener.closed

Get handle to a window by name

I mentioned there's no way to just get the window handle by name in the comments. However, I did some research and found that the following works in FF/IE/Chrome; it's a hack, I didn't see it mentioned anywhere as the expected behavior, so I wouldn't rely on it too much, but it was fun to find it works! In my code, I would still just make sure to pass around the required handles.

//opened a window without storing a handle, but gave it a name
window.open('/some/url', 'xxx');

// now I need to get a reference to that window
// Calling open without setting a url gets you
// a reference and doesn't reload the window
var win = window.open('', 'xxx')


Use try{} and catch(err){}.

try{
window.opener.document.body.getElementById('#elementId'); // do some action with window. opener
}
catch(err){
// if we are here then probably there is no window.opener
window.close(); // closing this window or whatever you want
}


Try the following code:

if (!!window) {
  console.log('Exist');
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜