gpt4 book ai didi

javascript - 窗口是否可以关闭?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:15:34 28 4
gpt4 key购买 nike

我需要知道 window.close() 是否真的要关闭窗口。这不是 Close window - How to determine how window was opened? 的副本因为该解决方案依赖于检查 window.name,这并非万无一失;弹出窗口可以用不同的名称打开,但仍然可以通过 window.close() 关闭。

我不能只检查 window.opener 是否定义为空,因为在 Firefox 和 Chrome 中,如果用户关闭打开器,window.opener 会被设置为 null。例如:

// In parent window:
window.open();

// In child window:
console.log(window.opener); // outputs a Window object

// Now, click the X on the parent window.

// Continue below in child window:
console.log(window.opener); // outputs null
// However, you can still close the window!
window.close(); // closes the child window

另一方面,如果用户在新标签页中加载了包含此代码的页面:

console.log(window.opener); // also outputs null
window.close(); // doesn't work; window remains open

然后 Firefox 在错误控制台中提示脚本无法关闭不是由脚本打开的窗口,而 Chrome 什么也不做。

我需要检查 window.close() 是否会关闭窗口的原因是,如果窗口保持打开状态,我想转到另一个地址。我想到了这样做:

// Try to close window.
window.close();
// If the window is still open after three seconds, go to another page.
setTimeout(function(){
// For testing purposes:
alert("Not closed!");
// What I want to do:
window.location = "http://www.example.com/";
}, 3000);

但是,三秒的滞后会让我的应用程序对用户来说看起来很慢。那不行。在我的电脑上,1 毫秒的延迟足以让窗口关闭;只有在 window 保持打开状态时才会发出警报。但是,我需要有人确认这对所有计算机都是正确的。这也不起作用:

try{
// This will not throw an error regardless of
// whether the window was actually closed:
window.close();
}catch(e){
// This never happens:
console.log("Could not close window");
}

简而言之,我只需要一种在调用 window.close() 之前或之后通过 JavaScript 了解窗口是否真正关闭的方法。我该怎么做?

最佳答案

只需调用 window.close() 然后检查 window.closed 看它是否关闭。这也将捕获您尝试使用 beforeunload 处理程序 close() 页面并且用户选择不让它关闭的情况......

哦,根据 window.close() 规范,如果窗口要关闭,则在返回之前同步更新 window.closed,因此您不必担心关于超时等等。

关于javascript - 窗口是否可以关闭?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21079516/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com