普通javascript不能随意关闭窗口。这是一个安全特性,在一段时间前推出,以阻止各种恶意利用和烦恼。
来自window.close()的最新工作规范:
The close() method on Window objects should, if all the following conditions are met, close the browsing context A:
The corresponding browsing context A is script-closable.
The browsing context of the incumbent script is familiar with the browsing context A.
The browsing context of the incumbent script is allowed to navigate the browsing context A.
A browsing context is script-closable if it is an auxiliary browsing context that was created by a script (as opposed to by an action of the user), or if it is a browsing context whose session history contains only one Document.
这意味着,除了一个小例外,javascript必须不允许关闭一个没有被同一javascript打开的窗口。
Chrome允许这种例外——它不适用于用户脚本——但Firefox不允许。Firefox的实现直截了当地说:
此方法只允许被脚本使用该窗口打开的窗口调用。开放的方法。
如果你想用window。关闭Greasemonkey / Tampermonkey / userscript,你会得到:
Firefox:错误消息“脚本不能关闭未由脚本打开的窗口”。
Chrome:只是无声地失败。
长期解决方案:
解决这个问题的最好方法是做一个Chrome扩展和/或Firefox插件。这些可以可靠地关闭当前窗口。
但是,由于窗口存在安全隐患。接近,对于Greasemonkey/Tampermonkey脚本来说要少得多;Greasemonkey和Tampermonkey可以在它们的API中合理地提供此功能(实际上是为您打包了扩展工作)。
考虑提出一个特性请求。
俗气的变通方法:
Chrome目前很容易受到“自重定向”漏洞的攻击。所以像这样的代码在一般情况下是有效的:
open(location, '_self').close();
这是错误的行为,我认为,现在(大约在2015年4月)大部分被阻止。它仍然会从注入的代码,只有当标签是新打开的,并在浏览历史中没有页面。所以它只在很小的情况下有用。
然而,变种仍然适用于Chrome (v43和v44)和Tampermonkey (v3.11或更高版本)。使用显式的@grant和普通的window.close()。例如:
// ==UserScript==
// @name window.close demo
// @include http://YOUR_SERVER.COM/YOUR_PATH/*
// @grant GM_addStyle
// ==/UserScript==
setTimeout (window.close, 5000);
感谢zanetu的更新。注意,如果只有一个选项卡打开,这将不起作用。它只关闭额外的选项卡。
Firefox对这种攻击是安全的。所以,javascript唯一的方法就是削弱安全设置,一次一个浏览器。
你可以打开about:config和set
Allow_scripts_to_close_windows为true。
如果您的脚本是供个人使用的,那么就这样做吧。如果你让其他人打开这个设置,他们会明智而合理地带着偏见拒绝。
目前Chrome没有相应的设置。