根据许多规则和安全功能,window.close()
仅在特定情况下有效:
From the latest working spec对于 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.
我有一个允许用户关闭新窗口的 Web 应用程序,它工作正常,除非不遵守上述规则。
我正在寻找的是检测 close() 函数何时起作用,并且只在这种情况下显示关闭按钮。
我发现有关 window.opener
的信息,它从打开它的窗口返回一个引用。但它不起作用。
if(window.opener != null){
//show button
}
也许这是因为新窗口是使用“右键单击 -> 在新选项卡中打开”而不是脚本打开的。当以这种方式打开选项卡时 window.close()
起作用,我只想检测 window.close()
何时起作用。
有什么想法吗?
最佳答案
根据文档,如果给定上下文的 session 历史记录长度为 1(这正是您在新选项卡/窗口中打开链接时发生的情况),该窗口也可以通过脚本关闭。您需要将其添加到检查器中。
if(window.opener != null || window.history.length == 1){
//show button
}
关于javascript - 在使用之前检测 window.close() 是否有效(JavaScript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50592250/