-2

I try to use this line to open up a new window and at the same time close the window from where the user clicked the link. It do open a new window but I get the following warning when trying to close the window. "Scripts may close only the windows that were opened by them"

<a href="#"><img src="images/close.png" onClick="CloseMe ('newwindow.html'),top.window.close();"></a>

<script language="JavaScript" type="text/javascript">
function CloseMe(url,h,w) {
 popupWin = window.open(url, 'popup', 'height=' + h + ',width=' + w + ',top=0,left=0');
}
</script>
MTplus
  • 2,077
  • 4
  • 34
  • 51
  • 1
    Javascript is only allowed to close the window if it was Javascript that opened it in the first place. – Niet the Dark Absol Jul 09 '20 at 09:47
  • 1
    The error message clearly states the issue. You cannot close a window using JS if it wasn't opened using JS – Anurag Srivastava Jul 09 '20 at 09:47
  • Can anyone then please tell me how can close the window? – MTplus Jul 09 '20 at 09:50
  • Why not redirecting the site instead of using a popup? It would load the new site in the current window and therefore unload the current site. – Lain Jul 09 '20 at 09:51
  • Is it really important that you close the current window? Why not just leave it there? If the user does not like it, they can close it themselves. – M0nst3R Jul 09 '20 at 09:52
  • 1
    Does this answer your question? [javascript close current window](https://stackoverflow.com/questions/23306882/javascript-close-current-window) – Anurag Srivastava Jul 09 '20 at 09:52

1 Answers1

1

The warning is right: Scripts are not allowed to close windows that were opened by the user and not a script.

So, you can close the window that you opened (and that window can also close itself), but you cannot close the other window that the user opened.

About your question how to close the window anyway: There is no way, it is not allowed! If you want to have a situation where you can close the previous window at any time, you need to use a script to open that window in the first place, then you can close it too. For example you could have your app initially just show a button "Enter application" which opens a new window using window.open with the actual application in it, and then calling window.close() will work inside of that window.

CherryDT
  • 25,571
  • 5
  • 49
  • 74