Eduardo Ponce de Leon
Eduardo Ponce de Leon

Reputation: 9696

Detect if window.close() will work before using it (JavaScript)

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?

Upvotes: 11

Views: 4995

Answers (2)

BoltKey
BoltKey

Reputation: 2198

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
}

Upvotes: 12

Lewis
Lewis

Reputation: 4595

As I understand it, there isn't a native way to do this. It is possible to check if window.close() has failed after the fact by checking if window.closed is false to detect an error. See here.

Your only option is to offer the functionality to close every window, or try to in all cases, and ask the user to close it manually if it fails - otherwise it cannot be closed by you, or any of your code, by definition. There isn't a way around that unfortunately. One option that might be worth trying would be to redirect them somewhere if the window cannot be closed programmatically, which you can verify easily after every attempt.

Upvotes: 2

Related Questions