The issue is that when I invoke window.close()
or self.close()
it doesn\'t close the window. Now there seems to be a belief that in Chrome you can\
I am using the method posted by Brock Adams and it even works in Firefox, if it's user initiated.
open(location, '_self').close();
I am calling it from a button press so it is user initiated, and it is still working fine using Chrome 35-40, Internet Explorer 11, Safari 7-8 and ALSO Firefox 29-35. I tested using version 8.1 of Windows and Mac OS X 10.6, 10.9 & 10.10 if that is different.
Self-Closing Window Code (on the page that closes itself)
The complete code to be used on the user-opened window that can close itself:
window_to_close.htm
JavaScript:
function quitBox(cmd)
{
if (cmd=='quit')
{
open(location, '_self').close();
}
return false;
}
HTML:
<input type="button" name="Quit" id="Quit" value="Quit" onclick="return quitBox('quit');" />
Try this test page: (Now tested in Chrome 40 and Firefox 35)
http://browserstrangeness.bitbucket.io/window_close_tester.htm
Window Opener Code (on a page that opens the above page)
To make this work, security-imposed cross browser compatibility requires that the window that is to be closed must have already been opened by the user clicking a button within the same site domain.
For example, the window that uses the method above to close itself, can be opened from a page using this code (code provided from my example page linked above):
window_close_tester.htm
JavaScript:
function open_a_window()
{
window.open("window_to_close.htm");
return false;
}
HTML:
<input type="button" onclick="return open_a_window();" value="Open New Window/Tab" />
For TamperMonkey:
@grant window.close
Ref: https://www.tampermonkey.net/documentation.php#_grant
In my case, the page needed to close, but may have been opened by a link and thus window.close
would fail.
The solution I chose is to issue the window.close
, followed by a window.setTimeout
that redirects to a different page.
That way, if window.close
succeeds, execution on that page stops, but if it fails, in a second, it will redirect to a different page.
window.close();
window.setTimeout(function(){location.href = '/some-page.php';},1000);
The below code worked for me -
window.open('location', '_self', '');
window.close();
Tested on Chrome 43.0.2357.81