ChatGPT解决这个技术问题 Extra ChatGPT

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?

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 !
It is not possible. Read this. stackoverflow.com/a/19768082/4671932
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 mentioned). 2, not mentioned here: You can close the tab only if window.top.opener (the "parent" window) isn't null.
windows.close() not working in the angular. It gives me Scripts may close only the windows that were opened by them. Warning.

R
Rublacava

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.


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.
-1 Doesn't work chrome 30 PC the other answers showing to open a window in the current tab and then close it work
In about:config dom.allow_scripts_to_close_windows = true might be the solution in Firefox (might be a big security risk!)
The browser does not allow this behavior. Javascript can only close a tab that it opened.
This works (at least) in Chrome 62: <button type="button" onclick="window.open('', '_self', ''); window.close();">Discard</button> See also this article
D
Daniel Shen

Try this

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

Working in Firefox 31.0
Bad side of this solution is that a get request is sent to server. But on the other side, I haven't found any other solution.
Doing this from the Chrome console outputs "Scripts may close only the windows that were opened by it"
Not working in chrome 60.0.3079.0: "Scripts may close only the windows that were opened by it."
P
Palesz

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>

Simpler: open(location, '_self').close();
This worked well in IE 11, but didn't work in Chrome 38
G
Guy Schalnat

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


This works (at least) in Chrome 62: <button type="button" onclick="window.open('', '_self', ''); window.close();">Discard</button> See also this article
@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.
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.
M
Mackey Johnstone

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

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

https://i.stack.imgur.com/CucLe.png

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.


"Scripts may close only the windows that were opened by it." on Chrome 50.
L
Leniel Maccaferri

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>

A lot of other techniques here did not work for me, this did, I am using Google Chrome Version 88.0.4324.182 (Official Build) (64-bit)
not working in chrome 96
T
Thailandian

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.


Chrome: 'Uncaught TypeError: Cannot set property 'innerHTML' of null'
J
Julesfrog

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.


Not owrking on chrome "Scripts may close only the windows that were opened by it."
N
Nikos Hidalgo

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>

This works in every modern browser. IE11 and Edge 17 show a confirm alert but it still works.
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.
p
pikax
<button class="closeButton" style="cursor: pointer" onclick="window.close();">Close Window</button>

this did the work for me


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.
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.
s
sir

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.


That's the only reliable option for chrome
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.
V
VityaSchel

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!


C
Community

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>

U
UserName Name

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

This is overly complex - both in terms of the JS used, but also unnecessarily brining HTML into the mix.
This is the answer which helped me!
D
Diego

Here's how you would create such a link:

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