How to tell if a window exists in Javascript?

前端 未结 4 1948
情话喂你
情话喂你 2020-12-30 05:07

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 th

相关标签:
4条回答
  • 2020-12-30 05:37

    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
    }
    
    0 讨论(0)
  • 2020-12-30 05:45

    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')
    
    0 讨论(0)
  • 2020-12-30 05:49
    if(window.opener && !window.opener.closed)
        alert('Yup, still there.');
    
    0 讨论(0)
  • 2020-12-30 05:54

    Try the following code:

    if (!!window) {
      console.log('Exist');
    }
    
    0 讨论(0)
提交回复
热议问题