Javascript 如何关闭浏览器窗口中的当前选项卡?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2076299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:41:09  来源:igfitidea点击:

How to close current tab in a browser window?

javascripthtmlhyperlink

提问by Naveed

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?

怎么做到呢?有什么建议?

回答by cletus

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

您将需要 Javascript 来执行此操作。使用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:

使用 HTML:

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

or:

或者:

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

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

return false在此处阻止事件的默认行为。否则浏览器将尝试访问该 URL(显然不是)。

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

现在window.confirm()对话框上的选项将是“确定”和“取消”(不是“是”和“否”)。如果你真的想要 Yes 和 No 你需要创建某种模态 Javascript 对话框。

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.

注意:与上述存在浏览器特定的差异。如果您使用 Javascript(通过window.open())打开窗口,那么您可以使用 javascript 关闭窗口。Firefox 不允许您关闭其他窗口。我相信 IE 会要求用户确认。其他浏览器可能会有所不同。

回答by Daniel Shen

Try this

尝试这个

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

回答by Palesz

This method works in Chrome and IE:

此方法适用于 Chrome 和 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>

回答by 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).

据我所知,在 Chrome 或 FireFox 中不再可能。它在 IE 中仍然是可能的(至少 pre-Edge)。

回答by Guy Schalnat

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.

这将为您关闭当前选项卡。

回答by Thailandian

The following works for me in Chrome 41:

以下在 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 reallyopened by JS, but FF, at least, cannot be duped into closing a tab by opening new content inside that tab.

我已经为 FF 尝试了几个想法,包括打开一个实际的网页,但似乎没有任何效果。据我所知,任何浏览器都会关闭带有 xxx.close() 的选项卡或窗口,如果它真的是由 JS 打开的,但至少 FF 不能通过在该选项卡中打开新内容来欺骗关闭选项卡。

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

仔细想想这是有道理的 - 用户很可能不希望 JS 关闭具有有用历史记录的选项卡或窗口。

回答by Julesfrog

Tested successfully in FF 18 and Chrome 24:

在 FF 18 和 Chrome 24 中测试成功:

Insert in head:

插入头部:

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

HTML:

HTML:

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

Credits go to Marcos J. Drake.

致谢Marcos J. Drake

回答by Bhavin Shah

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>

回答by killstreet

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

对于仍在访问此页面的人,您只能关闭由脚本打开的选项卡或使用带有目标 _blank 的 HTML 锚标记。两者都可以使用

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

回答by 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 in 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.

注意:这些解决方法是在考虑到本地托管站点的情况下完成的,并且(Edge 除外)需要专门配置浏览器,因此对于公共托管站点来说并不理想。

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.

上下文:过去,jQuery 脚本window.close()能够在大多数浏览器上毫无问题地关闭当前选项卡。但是,现代浏览器不再支持此脚本,这可能是出于安全原因。

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 canuse the window.close() method ifyou include the // @grant window.closein the UserScript header of TamperMonkey.

Chrome 不允许运行 window.close() 脚本,如果您尝试使用它,则不会发生任何事情。但是,通过使用 Chrome 插件 TamperMonkey,如果您将 包含在 TamperMonkey 的 UserScript 标头中,我们可以使用 window.close() 方法。// @grant window.close

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:

例如,我的脚本(当点击 id = 'close_page' 的按钮并且在浏览器弹出窗口中按下 'yes' 时触发)如下所示:

// ==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:configthen search and find the dom.allow_scripts_to_close_windowspreference and switch it from false to true.

Firefox 有一个高级设置,您可以启用该设置以允许脚本关闭窗口,从而有效地启用该window.close()方法。要启用此设置,请转到about:config,然后搜索并找到dom.allow_scripts_to_close_windows首选项并将其从 false 切换为 true。

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

这允许您像使用window.close()任何其他脚本一样直接在 jQuery 文件中使用该方法。

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

例如,此脚本在首选项设置为 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.

这比 Chrome 解决方法要好得多,因为它允许用户关闭当前选项卡,即使它是唯一打开的选项卡,并且不需要第三方插件。然而,一个缺点是它还使该脚本能够由不同的网站(不仅仅是您打算在其上使用的网站)运行,因此可能存在安全隐患,尽管我无法想象关闭当前选项卡会特别危险。

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.

令人失望的是,Edge 实际上在我尝试过的所有 3 种浏览器中表现最好,并且window.close()无需任何配置即可使用该方法。当window.close()脚本运行时,一个额外的弹出窗口会提醒您该页面正在尝试关闭当前选项卡并询问您是否要继续。

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.

最后说明:Chrome 和 Firefox 的解决方案是浏览器有意禁用的解决方法,可能是出于安全原因。它们也都要求用户事先将他们的浏览器配置为兼容,因此对于供公共使用的站点来说可能不可行,但对于像我这样的本地托管解决方案来说是理想的。

Hope this helped! :)

希望这有帮助!:)