Shubham
Shubham

Reputation: 1793

How to close browser tab

I am not able to close the current browser tab using javascript.

I tried-

    window.close(); //1

    window.open("", '_self');//2
    setTimeout(function(){
        window.close();
    },100);

    window.open('','_parent',''); //3
    window.close();

    window.top.opener=null; //4
    window.close();

Nothing is working for me in chrome

Upvotes: 3

Views: 35913

Answers (6)

Mada Aryakusumah
Mada Aryakusumah

Reputation: 611

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

See my original answer on this thread

Upvotes: 6

AbdusSalam
AbdusSalam

Reputation: 440

<script src="~/Scripts/jquery-1.8.2.js"></script>
<script>
    var win;
    $(document).ready(function () {
        var url = 'this tab url';
        win = window.open(url, '_self');
        window.stop();                
    });
    function closeWindow() {
        win.close();
    }
</script>

Then in html

<a href="javascript:closeWindow();">close</a>

If there are multiple tusk to load then wait some times by this

setTimeout(
  function() 
  {
    //do something special
   //window.stop(); 
  }, 5000);

Upvotes: 0

&#193;lvaro Gonz&#225;lez
&#193;lvaro Gonz&#225;lez

Reputation: 146390

As already stated, you can only close windows/tabs that you previously opened yourself. None of your code snippets comply with this.

If you want to close a child window from its parent you need to store a reference to it, e.g.:

var child = window.open("");
setTimeout(function(){
    child.close();
},100);

Demo

If you want to close the child window from itself you need to run the code inside the window.

If you overwrite current document with a blank one your your code disappears.


Now, Chrome is a special beast. It opens each tab in a different process. That means that several good old techniques that involve different tabs do not work at all. For instance, you can't even use the target parameter in window.open() to share a window.

Upvotes: 0

Kiyarash
Kiyarash

Reputation: 2578

As much as I know, you can't close browser tab using Javascript. This is not a common way to do...

I'm not sure if you can do this, because some browsers do not have any tabs at all...

But try this, may be it work for you :

window.top.close();

reference : Another Question in stackoverflow

OR :

<a href="javascript:window.open('','_self').close();">close</a>

Upvotes: 1

ozil
ozil

Reputation: 7117

You can only close windows/tabs that you create yourself. That is, you cannot programmatically close a window/tab that the user creates.

For example, if you create a window with window.open() you can close it with window.close().

Upvotes: 0

QBernard
QBernard

Reputation: 383

window.close method is only allowed to be called for windows that were opened by a script using the window.open method.

Upvotes: 15

Related Questions