584

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?

Fabian N.
  • 3,807
  • 2
  • 23
  • 46
Naveed
  • 41,517
  • 32
  • 98
  • 131
  • 2
    I might be late here but this is prevented by the browsers for a reason.

    Think of yourself trying to close a window again and again and it's not closing as its doing the "**if no**" part from your question which is 'do nothing'.

    This will be irritating for sure !
    – Muhammad Osama Mar 16 '19 at 08:54
  • It is not possible. Read this. https://stackoverflow.com/a/19768082/4671932 – iamandrewluca Aug 26 '20 at 22:52
  • For anyone trying to close the tab programatically, I have two things to add (TL:DR;) `1` You can only close tabs that were opened with javascript (as [Ryan Joy](https://stackoverflow.com/questions/2076299/how-to-close-current-tab-in-a-browser-window#comment2006744_2076307) mentioned). `2`, not mentioned here: _You can close the tab_ only if `window.top.opener` (the "parent" window) isn't null. – Nico Nov 25 '20 at 09:10
  • windows.close() not working in the angular. It gives me Scripts may close only the windows that were opened by them. Warning. – Margi212 Jul 13 '21 at 05:15
  • The page you want to close paste the following code: Close – Omid Shagiwal Nov 06 '22 at 09:57

23 Answers23

661

You will need Javascript to do this. Use window.close():

close();

Note: the current tab is implied. This is equivalent:

window.close();

or you can specify a different window.

So:

function close_window() {
  if (confirm("Close Window?")) {
    close();
  }
}

with HTML:

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

or:

<a href="#" onclick="close_window();return false;">close</a>

You return false here to prevent the default behavior for the event. Otherwise the browser will attempt to go to that URL (which it obviously isn't).

Now the options on the window.confirm() dialog box will be OK and Cancel (not Yes and No). If you really want Yes and No you'll need to create some kind of modal Javascript dialog box.

Note: there is browser-specific differences with the above. If you opened the window with Javascript (via window.open()) then you are allowed to close the window with javascript. Firefox disallows you from closing other windows. I believe IE will ask the user for confirmation. Other browsers may vary.

Rublacava
  • 414
  • 1
  • 4
  • 16
cletus
  • 616,129
  • 168
  • 910
  • 942
  • 521
    You can't close any tab via JavaScript. "This method is only allowed to be called for windows that were opened by a script using the window.open method." In other words, you can only use JavaScript to close a window/tab that was spawned via JavaScript. – Ryan Joy Jan 16 '10 at 05:46
  • @atxryan And I believe the *same domain/origin policy* applies as well. – Justin Johnson Jan 16 '10 at 08:20
  • 9
    -1 Doesn't work chrome 30 PC the other answers showing to open a window in the current tab and then close it work – markasoftware Aug 11 '13 at 20:17
  • 2
    In `about:config` `dom.allow_scripts_to_close_windows = true` might be the solution in Firefox (might be a big security risk!) – Nepomuk Pajonk Mar 19 '14 at 12:11
  • 9
    The browser does not allow this behavior. Javascript can only close a tab that it opened. – Edward Kennedy Jul 30 '14 at 00:42
  • for me as it is not closing instead of location(path) I'm Using window open '_self' but it is still not closing as if I'm opening by window – UmaShankar Mar 08 '16 at 10:46
  • Working for me in Safari 9.0.2 for browser windows opened by python.webbrowser module. So I guess "not working safari browser" depends on exactly how you are trying to use it. – Simon Kissane Jun 11 '16 at 05:55
  • Chrome console log message: Scripts may close only the windows that were opened by it. – Roman Losev Oct 28 '16 at 09:49
  • I'm opening the new tab via Javascript, but `window.close();` still not working. – Mousa Alfhaily Mar 20 '17 at 15:56
  • Not working in Chrome version 58: `Scripts may close only the windows that were opened by it.` – doubleOrt Aug 31 '17 at 18:41
  • 2
    This works (at least) in Chrome 62: `` [See also this article](http://www.yournewdesigner.com/css-experiments/javascript-window-close-firefox.html) – hering Nov 23 '17 at 14:30
  • In most cases you may just redirect a user to it's browser home page https://stackoverflow.com/questions/1369450/sending-user-to-their-browsers-home-page-using-javascript – Sergey Ponomarev May 13 '18 at 20:43
  • 1
    Stop fretting people... This is an old answer and now this method is obsolete if you don't use window.open() method to open the page in first place. – zainul Jul 19 '18 at 07:56
  • Does not work. "Scripts may close only the windows that were opened by it." – César León Mar 20 '19 at 15:30
  • Is there also a HTML version that works without quotation marks? I want to know for… reasons… ;) – Fabian Röling May 09 '19 at 22:54
  • It is not possible anymore. https://stackoverflow.com/a/19768082/4671932 – iamandrewluca Aug 26 '20 at 22:53
  • windows.close() not working in the angular. It gives me Scripts may close only the windows that were opened by them. Warning. – Margi212 Jul 13 '21 at 05:16
  • This solution will only work if the window was opened by `window.open(...)`, refer to [my solution](https://stackoverflow.com/a/74140365/16359609) – RixTheTyrunt Oct 20 '22 at 13:08
265

Try this

<a href="javascript:window.open('','_self').close();">close</a>
Daniel Shen
  • 2,986
  • 1
  • 14
  • 13
66

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>
Palesz
  • 2,104
  • 18
  • 20
44

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

Guy Schalnat
  • 1,697
  • 15
  • 26
  • 3
    This works (at least) in Chrome 62: `` [See also this article](http://www.yournewdesigner.com/css-experiments/javascript-window-close-firefox.html) – hering Nov 23 '17 at 14:30
  • 1
    @hering Well, the article is from 2006, but if you found something that works, that's great news and perhaps will help people who read down this far. Thanks for sharing. – Guy Schalnat Nov 27 '17 at 14:22
  • The question was about closing the current active tab from within that tab. As you say, it's not possible in Chrome or Firefox. This should be the accepted answer. – decates Sep 20 '18 at 09:30
32

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.

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, with non-configured browsers (typical for publicly hosted sites) having limited functionality.



Context:

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

Current Functionality:

window.close() will work on tabs opened by a script, or by an anchor with target="_blank" (opened in a new tab) without requiring any additional setup or configuration.

See @killstreet's comment on @calios's answer


Browser Specific work-arounds:

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. Specifically, it cannot close the tab if it would cause the window to close.


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

MS Edge close tab confirm box


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.

18

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.

13

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.

Thailandian
  • 577
  • 5
  • 14
  • Chrome: 'Uncaught TypeError: Cannot set property 'innerHTML' of null' – Francisco Corrales Morales Jul 02 '16 at 07:31
  • Positive review given. Even if document.write is frown upon due to some details, still a good answer in my humble opinion. The proposed alternatives (document.createElement, .createTextNode, .innerHTML) are not as nice and this provides the opportunity to let the User know. I will set an answer without document.write Best regards – Ramon Maldio Sep 03 '23 at 03:13
11

window.close() doesn't work in 2k21 because Scripts may close only the windows that were opened by them.

BUT if the tab is opened in the browser not manually, but automatically - then window.close() works.

Automatically (when close() works):

  • <a href="/close" target="_blank"> the browser will open address in the new tab and this tab can be closed with close()
  • when new browser tab is opened from another application (when you click a link in Telegram/Whatsup/Outlook etc) - OS will open new tab and it can be closed with close()
  • when you open the with window.open('ya.ru') - for sure it can be closed with close()

Manually (when it doesn't work):

  • when you open fresh browser and type in the address.
  • when you click (+) to open new tab and type in the address
Mihey Mik
  • 1,643
  • 13
  • 18
9

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>
Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480
Bhavin Shah
  • 1,287
  • 13
  • 14
9

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>
Nikos Hidalgo
  • 3,666
  • 9
  • 25
  • 39
killstreet
  • 1,251
  • 2
  • 15
  • 37
  • 1
    This works in every modern browser. IE11 and Edge 17 show a confirm alert but it still works. – Fabian von Ellerts Oct 24 '19 at 15:21
  • I am having a hard time getting Angular app to actually log out from Adfs. Wonder if closing the tab is the way to finally getting logged out. I will try this snippet then. – Tore Aurstad Sep 22 '21 at 22:15
8

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.

Julesfrog
  • 1,113
  • 3
  • 12
  • 19
7
<button class="closeButton" style="cursor: pointer" onclick="window.close();">Close Window</button>

this did the work for me

pikax
  • 259
  • 2
  • 3
  • Does not work in our React project, may be because we are using jsx rather than plain html and javascript. We get the same error as others: _Scripts may close only the windows that were opened by them._ – nickcin Mar 03 '21 at 14:57
  • What I find is in Chrome it works on local files (at least) when the tab was not first opened by pasting the URL into the browser bar. So, it had to be opened via double-click, from VSCode or anything else, but the yellow warning appeared and it did not work only when I opened a new tab via Ctrl-T and pasted the URL in. – Vasily Hall Mar 20 '21 at 09:50
4

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

calios
  • 525
  • 5
  • 13
  • 2
    It's not just tabs that have been opened by scripts, also an anchor tag with target _blank will be allowed to be closed. So far tested in chrome and firefox and both seem to allow to close tabs that have been opened by an anchor tag. – killstreet Apr 16 '19 at 10:05
4

It is guaranteed that the closing of tabs will not be tolerated in any future browsers. Using scripts like mentioned above will not work.

My solution was to use a Chrome Extension. A Chrome Extension can require tab manipulation permissions so it will be easy to handle the closing of any tab from the domain in which the extension's content script is active.

This is how the background script should look like:

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
    console.log(sender)
    console.log(message)
    if(message.closeThis) {
        closeTab(sender.tab.id)
    }
});

const closeTab = id => {
    console.log("Closing tab");
    chrome.tabs.remove(id);
}

The content script should look like this:

window.addEventListener("message", (event) => {
    // Only accept messages from ourselves
    if (event.source !== window)
        return;

    if (event.data.type && (event.data.type === "APPLICATION/CLOSE")) {
        console.log("Content script received APPLICATION/CLOSE event");
        chrome.runtime.sendMessage({closeThis: true});
    }
}, false);

Close the tab by calling this in your application (make sure the content scripts are enabled in your domain by specifying that in the manifest):

window.postMessage({ type: "APPLICATION/CLOSE" }, "*");

Be cautious when using this because Chrome Extensions' deployment can be a pain.

sir
  • 116
  • 4
  • 2
    That's the only reliable option for chrome – Georg Nov 24 '21 at 08:27
  • If this were the only viable option, facebook share links that open in a new tab and close after being shared, wouldn't work - and yet they do... in all browsers as far as I know. – Bruce May 31 '22 at 18:49
3

I just wanted to add that window.close() works in 2021, chrome 91, but not always. One of the cases when it works if there is no history in tab (you can't go back).

In my case I wanted to create self-destructing tab which closes after few seconds, but I was struggling with how to go to development server avoiding new tab, because apparently New tab is also tab and it is being saved in tab history :D I created link in about:blank tab with target=_blank attribute and it was leading to new tab where window.close() method finally worked!

VityaSchel
  • 579
  • 7
  • 18
1

Due to strict browser behaviors, window.close() will only work if it's opened by window.open(...)

But I made a solution for this!

  1. Add an empty hashtag with window.open(...) when it is NOT included
  2. When the perfect time for closing occurs, call window.close
  3. If 2. has returned an error, replace any hashtag or HTTP parameters with an empty hashtag and finally close the window
<button onclick="myFunction()">Close</button>
<script>
if (location.href.indexOf("#") == -1) {
    window.open(location.href + "#", "_self")
}

function myFunction() {
  try {
    window.close()
  } catch (err) {
    window.open(location.href.substring(0, location.href.indexOf("?")).substring(0, location.href.indexOf("#")) + "#", "_self")
    window.close()
  }
}
</script>

Type close in this live demo

RixTheTyrunt
  • 185
  • 3
  • 11
1

@VityaSchel added the most important note for me: https://stackoverflow.com/a/68035933/14678591

just wanted to add that window.close() works in 2021, chrome 91, but not always. One of the cases when it works if there is no history in tab (you can't go back).

In 2023 this behavior is also present in Firefox and Edge. New tabs without any page history that invoke window.close() indeed close themselves.




This could be a comment but my reputation is not high enough.

  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/33900399) – borchvm Feb 27 '23 at 15:32
  • 1
    Luckily I can reply to your comment without sufficient reputation as it is my own answer. This does indeed answer the question. It adds information that is otherwise missing in this thread. Eventhough it can be an answer on its own IMO, as stated, I would have prefered it to be a comment on another answer. What else should I do? Wait for enough reputation and come back? *If you are part of the stackoverflow team you should rethink, whether you really want to block new users from adding information to existing answers at all. Maybe a moderation by the OC of an answer would be enough* – Schlagmichdoch Feb 28 '23 at 16:17
1

Working for Chrome Version 111.0.xxxx.xxx

open(location, '_self').close();
Faizan Ahmad
  • 355
  • 3
  • 14
0

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>
Community
  • 1
  • 1
Mohsin Chaudhari
  • 105
  • 1
  • 1
  • 7
0

You can try this solution to trick the browser to close the current window using JavaScript + HTML:

JS:

function closeWindow() {
 if(window.confirm('Are you sure?')) {
  window.alert('Closing window')
  window.open('', '_self')
  window.close()
 }
 else {
  alert('Cancelled!')
 }
}

HTML:

Some content
<button onclick='closeWindow()'>Close Current Window!</button>
More content
UserName Name
  • 267
  • 2
  • 3
0

This is indeed possible, and is as simple as:

  window.opener = self
  window.close()

(confirm / cancel dialog omitted for brevity)

0
As stated previously by RixTheTyrunt here, due to security, Modern browser behavior does not allow window.close to work unless is opened by window.open or under other strict circumstances(like opening a new tab with minimal interaction).
When a page attempts to post a form, once that form interacts; window.close does not work(at least for me in several browsers: ff, edge, chrome...).

I liked a lot the solution by Thailandian, but contains document.write which is  frown upon.

I tried several solutions from this page and from other, but is by design.
This is what I considered a workaround. The main idea is to let the User know.

Best regards,
Thanks for reading.  

<script>
  // below will attempt to close if possible 
  function closing() {
    window.close(self);
    window.close('', '_parent', '');
    window.close('', '_self', '');
    // after several attempts will let the User know
    // below, will display a Full Screen Div with a Message for the User
    document.getElementById("msgDiv").style.display = 'block';
    // below, will Hide your Current Page Div to allow only the Previous Message
    document.getElementById("currentPage").style.display = 'none';
    // Below a timer to reload 
    setTimeout(function() {
      document.location.reload(true);
    }, 3000);
  }
</script>


<!-- Below is the Message for the User -->
<div align="center" id="msgDiv" style="display:none;width:100%;height:100vh">
  <h1><br>Unable to close Tab/Window with Scripts.<br><br>Please Close Tab/Window Manually in the Browser.<br><br>Thanks.<br><br><button style="cursor:pointer" onclick='document.location.reload(true);'>Reload</button></h1>
</div>
<!-- Below is the Current Page -->
<div id="currentPage" style="display:block;">
  <div style="position: absolute; right:1%; top: 2px; height: 22px; width: 30px; padding: 0em;" title="EXIT">
    <a href="#" onclick="closing()" style="cursor:pointer;text-decoration: underline;font-weight:900; background: tomato; border: 4px outset red; border-radius: 4px;">&times;</a></div>

  Your Page Content Should be Here <br>
  <br>
  <br>
  <form method="post" action="#">
    <div align="center" style="padding:14%;">
      <input style="font-size:1.5em" type="text" name="text" placeholder="Favorite Word" autofocus="autofocus">
      <input style="font-size:1.5em;cursor:pointer" type="submit" value="Go"></div>
  </form>
  <pre style="white-space:pre-wrap;">
As stated previously by RixTheTyrunt here, due to security, Modern browser behavior does not allow window.close to work unless is opened by window.open or under other strict circumstances(like opening a new tab with minimal interaction).
When a page attempts to post a form, once that form interacts; window.close does not work(at least for me in several browsers: ff, edge, chrome...).

I liked a lot the solution by Thailandian, but contains document.write which is  frown upon.

I tried several solutions from this page and from other, but is by design.
This is what I considered a workaround. The main idea is to let the User know.

Best regards,
Thanks for reading.  
</pre>
</div>
-3

Here's how you would create such a link:

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

Diego
  • 34,802
  • 21
  • 91
  • 134
Eric Mickelsen
  • 10,309
  • 2
  • 30
  • 41