JavaScript window.close() workaround method that works

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 Director/Senior Software Engineer, Photographer I test and create new CSS web page formatting hacks for BrowserHacks.com for the purpose of repairing web sites. PS-- CSS hacks are fun, but please attempt good CSS first unless in a bind. See Test Pages: https://browserstrangeness.bitbucket.io and https://browserstrangeness.github.io

Tagged with: , , , , , , , , , , , ,
Posted in Chrome, Computers, Cool Code, Firefox, Internet Explorer, Programming, Safari, Spartan, Tech, Web, Web Browser, Web Browsers
59 comments on “JavaScript window.close() workaround method that works
  1. Yeep says:

    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.

    Like

    • Jeff Clayton says:

      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

      Like

      • Yeep says:

        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?

        Liked by 1 person

      • Jeff Clayton says:

        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.

        Like

  2. Hani says:

    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.

    Like

  3. Hani says:

    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;
    }

    Like

  4. Jeff Clayton says:

    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.

    Like

  5. Hani says:

    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.

    Like

    • Jeff Clayton says:

      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.

      Like

  6. Mario says:

    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…………..

    Like

  7. Jeff Clayton says:

    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.

    Like

    • Mario says:

      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”;

      }

      //–>

      Liked by 2 people

  8. Mario says:

    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”;
    }

    ——————————–

    Liked by 1 person

  9. Jeff Clayton says:

    Sounds like you got it working, excellent!

    Liked by 1 person

  10. Frank says:

    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.

    Like

  11. arenas says:

    Hi,

    please, i can open, but not close the popup.

    http://arenas.pagesperso-orange.fr/frame/Namenstage-Kalender.html

    Thank’s for help
    @r

    Like

    • Jeff Clayton says:

      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.

      Like

  12. Nix says:

    worked worked worked (Y). Many thanks

    Like

  13. sdk says:

    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.

    Like

  14. 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.

    Like

    • Jeff Clayton says:

      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.

      Like

  15. Siv says:

    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.

    Like

  16. Preeti Arora says:

    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

    Like

    • Jeff Clayton says:

      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.

      Like

      • p says:

        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

        Like

      • Jeff Clayton says:

        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)

        Like

  17. Jeff Clayton says:

    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.)

    Like

  18. John Wood says:

    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.

    Like

  19. ADFtech says:

    Hi all,
    I want to display pop up before closing the window in ADF. Could you please help me.?

    Like

  20. Gunjan says:

    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?

    Like

    • Jeff Clayton says:

      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.

      Like

  21. Michael O'neill says:

    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

    Like

    • Jeff Clayton says:

      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.

      Like

  22. aruba246 says:

    Is it true we can use javascript to call a window iff the window opens using js?

    Like

  23. aruba246 says:

    We can use js to close a window iff the window opens using js..else js cant close it.Is this true?

    Like

  24. Tom says:

    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! 🙂

    Like

  25. Grand article continue comme ça !!

    Like

  26. dOlderOne says:

    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,

    Like

  27. Viper says:

    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

    Like

Leave a reply to dOlderOne Cancel reply