如何实现?有什么建议吗?
已在FF 18和Chrome 24中进行成功测试:
头部插入:
<script>
function closeWindow() {
window.open('','_parent','');
window.close();
}
</script>
HTML:
<a href="javascript:closeWindow();">Close Window</a>
<button class="closeButton" style="cursor: pointer" onclick="window.close();">Close Window</button>
有点晚了,但这就是我找到的...
window.close()
只有在使用 window.open() 方法打开窗口时才能正常工作(IE 是个例外)。
!(请参见下面 @killstreet 的评论,关于带有 target _blank 的锚标签)
TLDR:Chrome 和 Firefox 允许关闭它们。
你将会得到控制台错误: Scripts may not close windows that were not opened by script. 作为一个错误,除此之外什么也不会发生。
你可以在 URL 中添加一个唯一的参数来知道页面是否是由脚本打开的(如时间)- 但这只是一个 hack,而不是本地功能,并且在某些情况下会失败。
我找不到任何方法来确定页面是否是从 open() 打开的, 并且 close 不会抛出任何错误。 这将不会输出 "test":
try{
window.close();
}
catch (e){
console.log("text");
}
window.close()
在2021年的Chrome 91中有效,但并非总是如此。其中一个情况是,如果标签页中没有历史记录(您无法返回),则它可以正常工作。target=_blank
属性的链接,它导致新选项卡中的window.close()方法最终起作用!保证在未来的任何浏览器中都不允许关闭选项卡。使用像上面提到的脚本将不起作用。
我的解决方案是使用 Chrome扩展程序。Chrome扩展程序可以要求选项卡操作权限,因此轻松处理扩展内容脚本所在域中的任何选项卡关闭。
以下是背景脚本的样例:
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);
}
内容脚本应该如下所示:
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);
调用这个函数可以在应用程序中关闭标签页(确保在清单文件中指定域名并启用内容脚本):
window.postMessage({ type: "APPLICATION/CLOSE" }, "*");
使用此功能时应谨慎,因为Chrome扩展程序的部署可能比较麻烦。
window.opener = self
window.close()
window.close()
只有在通过 window.open(...)
打开的窗口中才能工作但我已经有了一个解决方案!
window.open(...)
添加一个空的哈希标记window.close
<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>
在此实时演示中输入close
@VityaSchel为我添加了最重要的注释: https://dev59.com/xXI95IYBdhLWcg3w8y6N#68035933
只想补充一点,window.close()在2021年的Chrome 91中可以使用,但并非总是有效。其中一个情况是当标签页中没有历史记录时(无法返回)。
在2023年,这种行为也存在于Firefox和Edge中。调用window.close()的新标签页确实会关闭自己,前提是它们没有任何页面历史记录。
这本来可以是一条评论,但我的声望还不够高。
适用于Chrome版本111.0.xxxx.xxx
open(location, '_self').close();
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
1
您只能关闭使用JavaScript打开的选项卡(如Ryan Joy所提到的)。2
,这里没有提到:只有当window.top.opener
(“父”窗口)不为null时,您才能关闭选项卡。 - Nico