[javascript] How to close current tab in a browser window?

I want to create a link on a webpage that would close the currently active tab in a browser without closing other tabs in the browser.
When the user clicks the close link, an alert message should appear asking the user to confirm with two buttons, "YES" and "NO". If the user clicks "YES", close that page and If "NO", do nothing.

How can it be done? Any suggestions?

This question is related to javascript html hyperlink

The answer is


Try this

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

This method works in Chrome and IE:

<a href="blablabla" onclick="setTimeout(function(){var ww = window.open(window.location, '_self'); ww.close(); }, 1000);">
    If you click on this the window will be closed after 1000ms
</a>

Try this as well. Working for me on all three major browsers.

<!-- saved from url=(0014)about:internet -->
<a href="#" onclick="javascript:window.close();opener.window.focus();" >Close Window</a>

<button class="closeButton" style="cursor: pointer" onclick="window.close();">Close Window</button>

this did the work for me


Tested successfully in FF 18 and Chrome 24:

Insert in head:

<script>
    function closeWindow() {
        window.open('','_parent','');
        window.close();
    }
</script> 

HTML:

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

Credits go to Marcos J. Drake.


Here's how you would create such a link:

<a href="javascript:if(confirm('Close window?'))window.close()">close</a>


The following works for me in Chrome 41:

function leave() {
  var myWindow = window.open("", "_self");
  myWindow.document.write("");
  setTimeout (function() {myWindow.close();},1000);
}

I've tried several ideas for FF including opening an actual web-page, but nothing seems to work. As far as I understand, any browser will close a tab or window with xxx.close() if it was really opened by JS, but FF, at least, cannot be duped into closing a tab by opening new content inside that tab.

That makes sense when you think about it - a user may well not want JS closing a tab or window that has useful history.


As for the people who are still visiting this page, you are only allowed to close a tab that is opened by a script OR by using the anchor tag of HTML with target _blank. Both those can be closed using the

<script>
    window.close();
</script>

Sorry for necroposting this, but I recently implemented a locally hosted site that had needed the ability to close the current browser tab and found some interesting workarounds that are not well documented anywhere I could find, so took it on myself to do so.

Note: These workarounds were done with a locally hosted site in mind, and (with the exception of Edge) require the browser to be specifically configured, so would not be ideal for publicly hosted sites.

Context: In the past, the jQuery script window.close() was able to close the current tab without a problem on most browsers. However, modern browsers no longer support this script, potentially for security reasons.

Google Chrome:

Chrome does not allow the window.close() script to be to be run and nothing happens if you try to use it. By using the Chrome plugin TamperMonkey however we can use the window.close() method if you include the // @grant window.close in the UserScript header of TamperMonkey.

For example, my script (which is triggered when a button with id = 'close_page' is clicked and if 'yes' is pressed on the browser popup) looks like:

// ==UserScript==
// @name         Close Tab Script
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  Closes current tab when triggered
// @author       Mackey Johnstone
// @match        http://localhost/index.php
// @grant        window.close
// @require      http://code.jquery.com/jquery-3.4.1.min.js
// ==/UserScript==

(function() {
    'use strict';
    $("#close_page").click(function() {
        var confirm_result = confirm("Are you sure you want to quit?");
        if (confirm_result == true) {
            window.close();
        }
    });
})();

Note: This solution can only close the tab if it is NOT the last tab open however. So effectively, it cannot close the tab if it would cause window to closes by being the last tab open.

Firefox:

Firefox has an advanced setting that you can enable to allow scripts to close windows, effectively enabling the window.close() method. To enable this setting go to about:config then search and find the dom.allow_scripts_to_close_windows preference and switch it from false to true.

This allows you to use the window.close() method directly in your jQuery file as you would any other script.

For example, this script works perfectly with the preference set to true:

<script>
  $("#close_page").click(function() {
    var confirm_result = confirm("Are you sure you want to quit?");
    if (confirm_result == true) {
      window.close();
    }
  });
</script>

This works much better than the Chrome workaround as it allows the user to close the current tab even if it is the only tab open, and doesn't require a third party plugin. The one downside however is that it also enables this script to be run by different websites (not just the one you are intending it to use on) so could potentially be a security hazard, although I cant imagine closing the current tab being particularly dangerous.

Edge:

Disappointingly Edge actually performed the best out of all 3 browsers I tried, and worked with the window.close() method without requiring any configuration. When the window.close() script is run, an additional popup alerts you that the page is trying to close the current tab and asks if you want to continue.

Edit: This was on the old version of Edge not based on chromium. I have not tested it, but imagine it will act similarly to Chrome on chromium based versions

enter image description here

Final Note: The solutions for both Chrome and Firefox are workarounds for something that the browsers intentionally disabled, potentially for security reasons. They also both require the user to configure their browsers up to be compatible before hand, so would likely not be viable for sites intended for public use, but are ideal for locally hosted solutions like mine.

Hope this helped! :)


It is possible. I searched the whole net for this, but once when i took one of microsoft's survey, I finally got the answer.

try this:

window.top.close();

this will close the current tab for you.


This is one way of solving the same, declare a JavaScript function like this

<script>
  function Exit() {
     var x=confirm('Are You sure want to exit:');
     if(x) window.close();
   }
</script>

Add the following line to the HTML to call the function using a <button>

<button name='closeIt' onClick="Exit()" >Click to exit </Button>

You can use window.close() to close browser tab.


As far as I can tell, it no longer is possible in Chrome or FireFox. It may still be possible in IE (at least pre-Edge).


a bit late but this is what i found out...

window.close() will only work (IE is an exception) if the window that you are trying to close() was opened by a script using window.open() method.

!(please see the comment of @killstreet below about anchor tag with target _blank)

TLDR: chrome & firefox allow to close them.

you will get console error: Scripts may not close windows that were not opened by script. as an error and nothing else.

you could add a unique parameter in the URL to know if the page was opened from a script (like time) - but its just a hack and not a native functionality and will fail in some cases.

i couldn't find any way to know if the page was opened from a open() or not, and close will not throw and errors. this will NOT print "test":

try{
  window.close();
}
catch (e){
  console.log("text");
}

you can read in MDN more about the close() function


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment Wrapping a react-router Link in an html button How to make a hyperlink in telegram without using bots? React onClick and preventDefault() link refresh/redirect? How to put a link on a button with bootstrap? How link to any local file with markdown syntax? link with target="_blank" does not open in new tab in Chrome How to create a link to another PHP page How to determine the current language of a wordpress page when using polylang? How to change link color (Bootstrap) How can I make a clickable link in an NSAttributedString?