Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How know if a window can be closed with js

Tags:

javascript

So as it has been discussed elsewhere, a window can be closed by js using window.close() only if it has been opened by a script.

I have a page that offers a button to open a discussion window. The discussion window opens to a new tab with window.open(). The discussion page has a button that calls window.close(), which closes the discussion window and takes you back to previous tab, so you can continue from where you left off.

The problem is that if someone takes a the url directly to the discussion window, the close button does not work.

Is there a way to detect if the window will be closable with window.close(), so I can show the button only if it will work?

like image 591
alianos- Avatar asked Jun 01 '15 14:06

alianos-


People also ask

Can a window close itself JavaScript?

JavaScript does not allow one to close a window opened by the user, using the window. close() method due to security issues. However, we can close a window by using a workaround. The approach to be followed is by opening the current URL using JavaScript so that it could be closed with a script.

How do I close a window in JavaScript?

JavaScript provides an in-built function named close() to close the browser window that is opened by using window. open() method.

Can you close browser with JavaScript?

To close a window or tab that was opened using JavaScript, call window. close() .

How do you check if a tab is already open in JavaScript?

How do you check if a tab is already open in Javascript? if (+localStorage. tabCount > 0) alert('Already open! '); else localStorage.


2 Answers

You can check to see if window.opener is not null:

When a window is opened from another window, it maintains a reference to that first window as window.opener. If the current window has no opener, this method returns NULL. Windows Phone browser does not support window.opener. It is also not supported in IE if the opener is in a different security zone.

like image 129
James Thorpe Avatar answered Nov 12 '22 07:11

James Thorpe


You can try using the window.opener object, which returns a reference to the window that opened the current window (if it's another window), or NULL if the current window was not opened via JS.

if (window.opener) //Show button
like image 35
Drown Avatar answered Nov 12 '22 06:11

Drown