38

please help java script about close current window. this is my code and it does not work.

<input type="button" class="btn btn-success"
                     style="font-weight: bold; display: inline;"
                     value="Close"
                     onclick="closeMe()">
function closeMe()
{
    window.opener = self;
    window.close();
}

I tried this but it doesn't work either:

var win = window.open("", "_self");
win.close();
pbarney
  • 2,529
  • 4
  • 35
  • 49
Kuc Ku
  • 595
  • 1
  • 6
  • 12

14 Answers14

33

I know this is an old post, with a lot of changes since 2017, but I have found that I can close my current tab/window with the following now in 2019:

onClick="javascript:window.close('','_parent','');"
brc-dd
  • 10,788
  • 3
  • 47
  • 67
Errol Jacoby
  • 331
  • 3
  • 2
17

** Update **

Since posting the answer the latest versions of browsers prevent the command from working. I'll leave the answer visible but note it ONLY works on older browser versions.


Most browsers prevent you from closing windows with javascript that were not opened with window.open("https://example_url.com") however, it is still possible to close the current window using the following command:

window.open('','_self').close()

This loads a blank url (the first argument) in the current window (the second argument) and then instantaneously closes the window. This works because when close() is called, the current window has been opened by javascript.

Fowler
  • 514
  • 4
  • 11
8

You cannot close a window with javascript that you did not open. It will not work in chrome or firefox.

See https://stackoverflow.com/a/19768082/2623781 for more information.

Community
  • 1
  • 1
nate.merlin
  • 89
  • 1
  • 3
8

In JavaScript, we can close a window only if it is opened by using window.open method:

window.open('https://www.google.com');
window.close();

But to close a window which has not been opened using window.open(), you must

  1. Open any other URL or a blank page in the same tab
  2. Close this newly opened tab (this will work because it was opened by window.open())
window.open("", "_self");
window.close();
Aryan Beezadhur
  • 4,503
  • 4
  • 21
  • 42
Neha Soni
  • 3,935
  • 2
  • 10
  • 32
7

To close your current window using JS, do this. First open the current window to trick your current tab into thinking it has been opened by a script. Then close it using window.close(). The below script should go into the parent window, not the child window. You could run this after running the script to open the child.

<script type="text/javascript">
    window.open('','_parent',''); 
    window.close();
</script>
Pangamma
  • 731
  • 12
  • 28
  • Well that is a bummer. Did any of the other scripts work? Seems to be working for me still and I am using Chrome. What is your Chrome version? Mine is "Version 89.0.4389.128 (Official Build) (64-bit)". They may have patched this. @scythargon – Pangamma Apr 20 '21 at 18:01
  • Did not work for me with latest MSEdge. – cskwg Nov 30 '21 at 07:32
  • @cskwg Dang. That sucks. – Pangamma Dec 21 '21 at 19:53
5

Should be

<input type="button" class="btn btn-success"
                       style="font-weight: bold;display: inline;"
                       value="Close"
                       onclick="closeMe()">
<script>
function closeMe()
{
    window.opener = self;
    window.close();
}
</script>
nicael
  • 18,550
  • 13
  • 57
  • 90
  • 1
    Thanks but it doesn't work bro, I click on close button an nothing happened, I read some search in google and other got same problem as me, since firefox 22 or 23 – Kuc Ku Apr 26 '14 at 05:19
1

If you can't close windows that aren't opened by the script, then you can destroy your page using this code:

document.getElementsByTagName ('html') [0] .remove ();
Ibnul Husainan
  • 221
  • 3
  • 6
0

I suggest to put id to the input, and close the window by callback function as the following:

<input id="close_window" type="button" class="btn btn-success"
                   style="font-weight: bold;display: inline;"
                   value="Close">

The callback function as the following:

<script>
   $('#close_window').on('click', function(){
      window.opener = self;
      window.close();
   });
</script>

I think sometimes onclick doesn't work, check the following answer also.

Community
  • 1
  • 1
Mohamed Yakout
  • 2,868
  • 1
  • 25
  • 45
0

I found this method by Jeff Clayton. It is working for me with Firefox 56 and Chrome (on Windows and Android).

Did not try all possibilities. On my side, I open a window with a target name in my A links, for example, target="mywindowname", so all my links open inside the same window name: mywindowname.

To open a new window:

<a href="example-link.html" target="mywindowname">New Window</a>

And then in the new window (inside example-link.html):

<a href="#" onclick="return quitBox('quit');"></a>

Javascript:

function quitBox(cmd) {   
    if (cmd=='quit') {
        open(location, '_self').close();
    }   
    return false;   
}

Hope this can help anyone else that is looking for a method to close a window. I tried a lot of other methods and this one is the best I found.

tung
  • 719
  • 2
  • 14
  • 30
MyraGe
  • 53
  • 1
  • 6
0

I have the same problem, the browser does not allow to close the tab, but I fixed it for me (12th of June 2021). The browserhistory must be 1 step (in chrome) to be able to use window.close(), if you open another window, then you have 2 steps, it will not work anymore. So I have to close and open new every window. If I add a onClick=windows.close event on every link and open this link in a new tab (target=_blank") the history stays at 1 step and it can always close the tab with windows.close().

<html>
<head></head>
<body>
    <div id="navbarToggler" >   
        <ul>
            <li>
                <a href class="closes" id="close"><script>document.write("[close]")</script></a>
            </li>     
            <li>
                <a class="nav-link text-nowrap " href="#" id="navbarDropdownMenuLink" >
                    gallery...does not close, it should be the Dropdownlink
                </a>
                    <div aria-labelledby="navbarDropdownMenuLink">
                    <a  href="#">self.html</a> Here you can link where you want, but every site needs the script
                    </div>
            </li>
        </ul>
    </div>
    <script>    
        document.querySelectorAll("a").forEach(function(x){
        x.setAttribute('target', '_blank');
        x.setAttribute('onClick', "window.setTimeout(function(){window.close();}, 50);");
        document.getElementById("close").setAttribute('target', '_self');
        document.getElementById("close").setAttribute('onClick', "window.close()");
        document.getElementById("navbarDropdownMenuLink").setAttribute('onclick', "");
        document.getElementById("navbarDropdownMenuLink").setAttribute('target', '_self');})
    </script>
</body></html>

The id 'navbarDropdownMenuLink' must be excluded by closing because it is a dropdownmenu. The id 'close' must be excluded by opening in a new tab because this is the link to close the current tab. The setTimeout function is needed for Firefox.

  • This example is for a website where you go from the main page to a gallery, which is opened in a new tab. In this gallery you can choose Items and go from one gallerysite to the next. At least you can close this opened tab, it does not matter how many gallery sides you have visited, the tab will be closed with windows.close(). – – Herrand Voller Jun 14 '21 at 15:55
0

None of the pure JS solutions I've been able to find have worked for me, at least not with all three of the browsers that I use to test my code: FF/Chrome/Edge. So I developed (perhaps a dirty) solution with jQuery+JS+PHP. Maybe somebody has come with a similar solution, but I was not able to find one. The button that closes the tab/window (of course, it must be opened by JS) has the following click event that creates a hidden field (uniquely named) before it submits the form.

$(".cancel").on('click', function (){
var $form = $(this).closest('form');
$form.append($("<input>", { type:'hidden', name: "cancel", value: ''}));
$form.submit();
})

At the top of the PHP script I have the following code

if (isset($_POST['cancel'])){
?><script>window.close();</script><?php
exit;
};

This solution has been tested with FF 98 and Chrome/Edge 99. If the page doesn't have a form, it can be created with the previous event.

Just in case the page has more than one forms and they submit to different pages, just add $form.attr({target: "_self", action: ''}); in the event!

rtO
  • 123
  • 1
  • 10
-1

Using javascript: window.close()

<input type="button" onclick="javascript: window.close()" class="btn btn-success" style="font-weight: bold; display: inline;" value="Close">
Sahil Thummar
  • 1,926
  • 16
  • 16
-2

TRY this out it works fine ...

<!DOCTYPE html>
<html>
<body>

<input type="button"  onclick="openWin()" value="open"/>
<input type="button"  onclick="closeWin()" value="close"/>

<script>
var myWindow;

function openWin()
{
myWindow = window.open("","myWindow","width=200,height=100");
myWindow.document.write("<p>This is 'myWindow'</p>");
}

function closeWin()
{
myWindow.close();
}
</script>

</body>
</html>

this works as you want it to work

Vicky
  • 694
  • 1
  • 8
  • 23
  • 1
    Thanks, but I knew it, I just want a close button to close that current page, not close a pop up. – Kuc Ku Apr 26 '14 at 05:17
-2

Works only in Google Chrome with self.close();. Tested in v48.

window.close() won't do what you want as the documentation for it clearly states that scripts may close only the windows that were opened by it.