NOTE: This script has 1 requirement that the page to be closed cannot be the original page. It must be opened as a new window. If you wish to close a page that has been posted via form, the page must first have still been opened in a separate window. If you are running any security programs, test the sample page first with them disabled if you are having issues. I have not seen any examples of modern browsers not working with this script if the above requirement has been met.
For those with hassles with window.close() or self.close() not working, there is a way for a JavaScript button to do this. You must use the complete code (HTML AND JAVASCRIPT BOTH!) for this to work. Scroll down to view all. A link to [ a working test page ] using script to open and script to close is included. Be sure to click the ‘Open in New Window/Tab’ button on the page to open a new popup window, and then click the ‘Close This Window/Tab’ button on the newly opened window.
Most versions do not work anymore due to security restrictions. The close option specification expects that it cannot be closed by anything other than the script that opened it… so this workaround basically attempts to reopen a window then close it:
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 35-40. I tested using version 8.1 of Windows and Mac OS X 10.6, 10.9 & 10.10.
—
The complete code:
The launcher window (window_close_tester.htm):
<script language="javascript"> function open_a_window() { window.open("window_to_close.htm"); return false; } </script> <input type="button" onclick="return open_a_window();" value="Open New Window/Tab" />
The opened window (window_to_close.htm):
<script language="javascript"> function quitBox(cmd) { if (cmd=='quit') { open(location, '_self').close(); } return false; } </script> <input type="button" onclick="return quitBox('quit');" value="Close This Window/Tab" />
Try this test page:
http://browserstrangeness.bitbucket.io/window_close_tester.htm
It is not working on Firefox 37 if the window is not open by a script, in which it means if I open your page via direct key in at the address bar: http://browserstrangeness.bitbucket.io/window_to_close.htm
Then the button will not function and firefox does not close the window.
LikeLike
Yeep, this is a page about a JavaScript method that works, meaning it requires JavaScript. I provided the entire code for it. You cannot choose to only use part of the code I provided if you want it to work.
If you scroll down, you will see that I provided an example that does work in Firefox 37 too. You may not have seen the words below stating the complete code on this very page and the complete script which does open it [copied from this example above]: Try this test page: http://browserstrangeness.bitbucket.org/window_close_tester.htm
LikeLike
Hi Jeff, yes, it works when the script is used to open the new Windows. But it always possible that someone bookmark the page and open directly next time. In that scenario, the window.close button will not work anymore, and it might not be good to have a non-functional button on the page.
Sorry for not clarify before I reply just now, It seems Firefox has completely prevent javascript to close the window as far as I have search.
Any idea?
LikeLiked by 1 person
Then I must post a message on the ‘bookmarked’ page that says to do what is necessary. Like I said, you have to follow the complete directions to make it work.
Based on your suggestion, I added instructions on that page to let people know they must go to the opener page to have it work right.
LikeLike
This codes does not work when the page is loaded through another page. I have a page with a submission form that leads to THANKS page. the close button on the thanks pages doesn’t work? any ideas? Thanks.
LikeLike
Could I see the page? Or at least a jsfiddle or github copy of the code you are using? I would love to see what is happening with it.
LikeLike
Hi Jeff;
well this code works in IE & Edge but not with chrome where it fails silently
P1.html
___________________________________
function openWindows()
{
window.open(“p2.html”, “_self”, ” “);
return false;
}
_____________________________________
p2/html
function CloseWindows()
{
open(location, ‘_self’).close();
return false;
}
LikeLike
You cannot do it like this: window.open(“p2.html”, “_self”, ” “); is causing it to fail. It works if you just do it like this: window.open(“p2.html”); which is what I showed in the example.
LikeLike
Yes, this is the point… I am trying to close the whole browser. because in my code it opens in full screen and take control. So, I need to it to be closed instead of opining new page.
LikeLike
It appears that to have it work in Chrome, the browser has to have opened it as a separate window in order to have a valid working ‘handle’ in javascript. This is a strange workaround so this is not surprising. iOS has similar issues.
LikeLike
let me see if u will able to help me
🙂
i use this code to check if the user have the popup enabled
var test_open_windows = window.open(“”,”test_open_windows”,”width=1,height=1″);
if (!test_open_windows) {
popupblock = true;
} else {
popupblock = false;
test_open_windows.close();
}
if (popupblock!= false) {
// POPUP BLOCK IS ACTIVE, redirect the user to a page and ask him to enable popups
window.location.href = “no_popup.php”;
}
the problem exist for no browser than Microsoft Edge
With this browser, infact, the page in wich the code is close itself instead of the opened one
i was trying to investigate this, so i puttend some alert() to see wich line caused the crash.
if i change the code in:
var test_open_windows = window.open(“”,”test_open_windows”,”width=1,height=1″);
if (!test_open_windows) {
popupblock = true;
} else {
popupblock = false;
test_open_windows.close();
}
if (popupblock!= false) {
// BLOCCO BLOCK IS ACTIVBE
alert(“popup are blocked”);
window.location.href = “no_popup.php”;
}
so, addinge a simple alert, the code work well
i don’t understund…………..
LikeLike
If the code is attempting to open and get a result before the response is received it will get an error. That is what is called a ‘race condition’. The alert pauses the code and allows the code time to receive the response. A settimeout to insert a delay before executing the result may solve this for you to give it time to receive a response. I do a slightly different thing in my own code – I set a div to say ‘popup blocked’, open a window, have the new child window use javascript to hide the blocked message in the parent window before closing itself. The user sees a quick window open and shut of course.
LikeLike
at the end i choosed to use the time delay
the other way was unaffoertable for me
so, as i’m in a php script i did so:
and then:
<!–
// VERIFY POPUP BLOCK
var popupblock = false;
var test = window.open('','','width=1,height=1');
if (!test) {
popupblock = true;
}else{
setTimeout(“test.close()”,1000)
test.close();
}
if (popupblock) {
// POPUP BLOCK ACTIVE
setTimeout(“window.location.href = ‘no_popup.php'”,1000)
window.location.href = “no_popup.php”;
}
//–>
LikeLiked by 2 people
of course at the beginning of the page i’ve:
LikeLike
it doesn’t show php code 🙂
I repost it here
—————————–
$user_agent = isset($_SERVER[‘HTTP_USER_AGENT’]) ? $_SERVER[‘HTTP_USER_AGENT’] : “NO”;
if (stripos($user_agent, ‘Edge’) !== false) {
$browser_name = “Edge”;
}else{
$browser_name = “altro”;
}
——————————–
LikeLiked by 1 person
Sounds like you got it working, excellent!
LikeLiked by 1 person
yes, and i’ve to say “THANKS TO YOU” !!!!
😀
LikeLiked by 1 person
You are most welcome! – The hardest bugs to fix are the ones that do not have errors in the code that can be fixed, but unforeseen surprises based on external causes.
LikeLike
Thanks a lot for this solution, I was starting to be crazy about Win 10 Mobile’s Edge not handling window.close properly, this is working even there.
LikeLike
Glad to hear it works on Windows Mobile – Thank you for the response!
LikeLike
Hi,
please, i can open, but not close the popup.
http://arenas.pagesperso-orange.fr/frame/Namenstage-Kalender.html
Thank’s for help
@r
LikeLike
Does the sample page I posted work properly for you? Both the open button and also the close button on the window that pops up? Important note- if you are attempting to close it automatically, that is often banned in browsers for security. A button is expected for most browser compatibility so it generally enforces the requirement that a human has to choose to open or close windows rather than a malware-styled script which opens or closes massive amounts of windows. I don’t see a ‘close’ button in your windows so I am betting that is the thing that you are missing.
LikeLike
Hi Sir,
Many thank for your reply!
@a
LikeLike
worked worked worked (Y). Many thanks
LikeLike
Glad you found it helpful!
LikeLike
Hello Jeff,
I am trying to close the chrome window using javascript but your solution doesn’t work for some reason.
chrome version: 53.0.2785.143
JS:
function quitBox(cmd){
alert(“Kindly save all necessary information. All your browser windows will be closed.”);
if(cmd==’quit’){
open(location, ‘_self’).close();
}
return false;
}
HTML:
Somehow it is not closing instead staying on the same page.
LikeLike
Did you open it with the javascript opener I provided? It requires that to generate the hook needed to close it. If you are just using the ‘close’ portion of the script you only have half the program.
LikeLike
Please run the http://browserstrangeness.bitbucket.org/window_close_tester.htm test page first in your browser and click the opener button. The opener truly is the key to making it work.
LikeLike
Jeff, your blog looks like the solution I have been trying to find for two months, Unfortunately, which I plug it in the markup with my other scripts, the button_click raises “return is a keyword”. I know very little about Java; PLEASE can you give a code suggestion? I use VS2015, C#, Windows10
Thanks for your great suggestion. I have tried more than 30 “solutions” to the problem of charting successive rows from a grid. Only the first works, it looks like an active close button is the only way to do it.
LikeLike
The compiling process may be complicating things, for that matter Java and JavaScript are not the same animal. There is almost always a workaround. Check me on email if you like for more in depth discussion as we both find the time — codertech (at) gmail (dot) com is good for that.
LikeLike
Hello Jeff,
I was looking for a code to close Chrome & Safari browser onclick of logout button.
The code which you provided works perfect when it opens in a new window.
Is there a possibility to open the window_Close page on the same window/tab instead of new window and close the tab when close button is clicked.
I tried the above option but the close doesn’t work when it opened on the same window/tab.
Can you pls help.
LikeLike
You are correct you can’t open in the old tab, it must be created with a new tab so it has a handle.
LikeLike
Hi Jeff,
Is there a way possible to close the window without using close method? Due to IE security patches we are facing this issue: On click of a hyperlink on parent window say domain one it opens up another new window say with domain 2. Now by the time control comes back to window.close function, reference to object window becomes undefined and it does not work properly.
Please provide your suggestion.
Thanks & Regards
Preeti Arora
LikeLike
The window-open and window-close method here uses these two and they need to match. The problem you are having sounds like not the first window, but subsequent ones, if I understand you correctly. To make the close feature work, it needs an opener link that ‘catches’ the window reference handle that can be used to close it. Secondary windows have different handles, and hyperlinks that are not javascripted with a window-open event do not save the handle of the windows they are opening. This method handles window popup security issues but not cross domain ones though (different security problem)… You could rewrite your own hyperlinks so they open in a different tab/window via link target, and then they would not ruin your original window – just people would have to hit a browser ‘x’ to close ones that you do not have control over in your first window. Otherwise you would have to effectively screen scrape and rewrite target pages to modify the links in them, but that can be very complicated.
LikeLike
Hi Jeff,
Thank you for your response.
We tried few approaches, but Still we are unable to handle this special case courtesy: Microsoft security patches 🙂
Since it was intermittent issue, it has been kept on hold for a while. In the mean time will be digging more for a possible workaround.
Thanks & Regards
Preeti Arora
LikeLike
No doubt — this solution works when something else doesn’t get in the way (security programming is almost 90% the culprit) – this sadly is the only method I have found that covers all browsers — the way you apparently need to solve it means that you have to control all content (meaning once you go out of your domain control you have no control of the results)
LikeLike
The other 10% would be if something were waxing your saved data – meaning something overwrites your windows handle variable, like another script would be one example. You may be searching for something that does not work without simply creating a web-spider that tracks links (so you can rewrite them as needed to remain within your application.)
LikeLike
Great job finding this “Diamond in the rough” of the various browsers.
It is nice to be able to close a “tab” that I opened, from JS/JQ.
LikeLike
Thank you and you are very welcome.
LikeLike
Hi all,
I want to display pop up before closing the window in ADF. Could you please help me.?
LikeLike
Hi Jeff,
This solution is working fine in browsers. But my page is opening in native app web view. And in webview it’s not able to close the window. My code base is same for normal browser site and native app.
Could you please advise what could be the issue?
LikeLike
The workaround is an attempt to create a handle for a window and use that handle to close it, despite security restrictions (due to spammers who opened and closed windows in web sites usually for ads or just to annoy people) that attempted to disable the ability to open or close windows in apps without user interaction — you may want to try to save the handle in a variable and see what you can do with it, like write to the window and see if the handle is not being lost. Webview is notoriously difficult to work with [many different devices out there with different code] so it may just simply not respond to that functionality or be buggy. Try opening a window with it, and in the opening window (not the new one) attempt to close it from the opener. If you can do that you may be able to pass the handle into a relatively non-scope-limited variable and call it later. It was very hard finding a way to do this in standard browsers, I am not surprised at the fact you are having issues with the web view which is not one of the big boys.
LikeLike
Please how do i set a timer to close a pop up
here is my javascript code.
window.onload = function () {
open(location, ‘_self’).close();
};
It works fine. I just want to set a timer to close after a few seconds.
Any help pls… i need it for a project asap
LikeLike
The pure javascript timers available are Window.setTimeout and Window.setInterval — there are other things you can attempt using something like jQuery. You would have your window.onload call one of those which in turn would call the open… command you are loading. If it does not work in your browser even with good code, it means the browser is blocking it due to security considerations.
LikeLike
Is it true we can use javascript to call a window iff the window opens using js?
LikeLike
Barring a program that blocks scripts or functionality, if you assign a variable as the handle of the window, then yes.
LikeLike
We can use js to close a window iff the window opens using js..else js cant close it.Is this true?
LikeLike
If you grab the newly opened window handle with the opening js, and pass it to the closing script, yes.
LikeLike
Doesnt work.
Try paste https://browserstrangeness.bitbucket.io/window_to_close.htm to your current tab then click to ‘Close This Window/Tab’.
‘Cause javascript doesnt owner current tab! 🙂
LikeLike
Thanks for letting me know the link was broken, I fixed it. It should have the proper results now.
LikeLike
Please change http://browserstrangeness.bitbucket.org/window_close_tester.htm
to https://browserstrangeness.bitbucket.io/window_close_tester.htm
from .org to .io
LikeLike
Thanks for catching that!
LikeLike
Grand article continue comme ça !!
LikeLike
Hello,
If you go to https://browserstrangeness.bitbucket.io/window_to_close.htm without going to that open page, it does not work.
Please help!
Thanks,
LikeLike
That is correct. If you do not use the code from the page opener, you do not have a file handle to use to close it. This apparently is a security feature built into browsers nowadays to keep malware people from closing your pages without you clicking a button or a link.
LikeLike
It was different, once.
LikeLike
Hi,
I am trying to execute url without window.open().
In IE Window.open() and window.close() worked fine but does not work in edge.
_self solved edge issue for me.
Edge keep showing url loading on application, any suggestion?
Thanks
LikeLike
Is this happening to you from the demo link in this page? I tried it and it worked just now with both versions edge (mshtml and the latest chromium): https://browserstrangeness.bitbucket.io/window_close_tester.htm I am thinking there might be something else going on. I am not able to reproduce the problem you are having.
LikeLike
FYI – If you are using the self close method without starting with a launcher, it is not compatible with all browsers. I am thinking you are referring to how you were trying it in your own code, possibly with a security program or extensions that may be causing you interference.
LikeLike