Kuc Ku
Kuc Ku

Reputation: 635

javascript close current window

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();

Upvotes: 42

Views: 310200

Answers (14)

Sahil Thummar
Sahil Thummar

Reputation: 2500

Using javascript: window.close()

<input type="button" onclick="javascript: window.close()" class="btn btn-success" style="font-weight: bold; display: inline;" value="Close">

Upvotes: -1

rtO
rtO

Reputation: 123

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!

Upvotes: 0

Errol Jacoby
Errol Jacoby

Reputation: 369

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','');"

Upvotes: 36

Herrand Voller
Herrand Voller

Reputation: 21

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.

Upvotes: 0

Neha Soni
Neha Soni

Reputation: 4704

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();

Upvotes: 14

Ibnul Husainan
Ibnul Husainan

Reputation: 231

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 ();

Upvotes: 1

Fowler
Fowler

Reputation: 534

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

Upvotes: 17

MyraGe
MyraGe

Reputation: 53

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.

Upvotes: 0

Pangamma
Pangamma

Reputation: 807

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>

Upvotes: 7

Razvan Stoenescu
Razvan Stoenescu

Reputation: 315

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.

Upvotes: -2

Mohamed Yakout
Mohamed Yakout

Reputation: 3046

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.

Upvotes: 0

nate.merlin
nate.merlin

Reputation: 99

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.

Upvotes: 9

nicael
nicael

Reputation: 19024

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>

Upvotes: 5

Vicky
Vicky

Reputation: 704

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

Upvotes: -2

Related Questions