According to many rules and security features, window.close()
will only work in specific cases:
From the latest working spec for window.close()
:
The
close()
method on Window objects should, if all the following conditions are met, close the browsing context A:
- The corresponding browsing context A is script-closable.
- The browsing context of the incumbent script is familiar with the browsing context A.
- The browsing context of the incumbent script is allowed to navigate the browsing context A.
A browsing context is script-closable if it is an auxiliary browsing context that was created by a script (as opposed to by an action of the user), or if it is a browsing context whose session history contains only one Document.
I have a web application that allows users to close new windows and it works fine, except when the rules above are not respected.
What I am looking for is to detect when the close() function will work and only show the close button in such case.
I found information talking about window.opener
that returns a reference from the window that opened it. But it doesn't work.
if(window.opener != null){
//show button
}
Maybe this is because the new window was opened using "right click -> open in new tab" and not a script. When tabs are opened in this fashion window.close()
works, I just want to detect when window.close()
will work.
Any ideas?
How to check if an opened browser window is closed or not in JavaScript? To check if an opened browser window is closed, you can use the closed property in referenced window object in JavaScript. The property returns a boolean true if the window is closed and false if the window is in the opened state.
close() method closes the current window, or the window on which it was called. This method can only be called on windows that were opened by a script using the Window.
A tab or window closing in a browser can be detected by using the beforeunload event. This can be used to alert the user in case some data is unsaved on the page, or the user has mistakenly navigated away from the current page by closing the tab or the browser.
If you store a reference to the child window when you call window. open() , then you can poll using setInterval() to see whether the window is still open using the window. closed property. The example below checks twice per second.
According to the docs, the window is script-closable also if session history of the given context is of length 1 (which is exactly what happens when you open a link in a new tab/window). You need to add that to your checker.
if(window.opener != null || window.history.length == 1){
//show button
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With