Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Window Close-able?

I need to know whether window.close() is actually going to close the window. This is not a duplicate of Close window - How to determine how window was opened? because that solution relies on checking window.name, which is not exactly foolproof; the popup could be opened with a different name but still be close-able via window.close().

I can't just check whether window.opener is defined or not null because in Firefox and Chrome, if the user closes the opener, window.opener gets set to null. For example:

// In parent window:
window.open();

// In child window:
console.log(window.opener); // outputs a Window object

// Now, click the X on the parent window.

// Continue below in child window:
console.log(window.opener); // outputs null
// However, you can still close the window!
window.close(); // closes the child window

On the other hand, if the user loaded a page with this code in a new tab:

console.log(window.opener); // also outputs null
window.close(); // doesn't work; window remains open

Firefox then complains in the Error Console about a script not being able to close windows not opened by scripts, and Chrome does nothing.

The reason that I need to check whether window.close() will close the window is that if the window remains open, I want to go to another address. I thought of doing it this way:

// Try to close window.
window.close();
// If the window is still open after three seconds, go to another page.
setTimeout(function(){
    // For testing purposes:
    alert("Not closed!");
    // What I want to do:
    window.location = "http://www.example.com/";
}, 3000);

However, a three-second lag would make my application seem slow to the user. That would not do. On my computer, a delay of 1 millisecond was sufficient to let the window close; the alert only happened if the window remained open. However, I would need someone to confirm that this is true for all computers. This also does not work:

try{
    // This will not throw an error regardless of
    // whether the window was actually closed:
    window.close();
}catch(e){
    // This never happens:
    console.log("Could not close window");
}

In short, I just need a way in JavaScript to know, either before or after calling window.close(), whether the window will actually close. How do I do that?

like image 640
wecsam Avatar asked Jan 12 '14 19:01

wecsam


1 Answers

Just call window.close() and then check window.closed to see whether it closed. That will also catch cases where you try to close() a page with a beforeunload handler and the user elects to not let it close....

Oh, and per spec window.close() updates window.closed synchronously before returning if the window is going to close, so you don't have to worry about timeouts and whatnot.

like image 74
Boris Zbarsky Avatar answered Sep 30 '22 01:09

Boris Zbarsky