我有一个要求,我通过 1 个窗口打开 2 个浏览器窗口。假设 A 打开 B 和 C。然后在其中一个子窗口(比如说 B)中,我打开另一个窗口(比如说 D)。现在,在这个新窗口 (D) 中,我想访问 C 的对象,以检查该窗口是打开还是关闭。
我可以在javascript中做到这一点吗?
我知道您可以通过 use window.open 和 window.opener 但这仅适用于浏览器窗口具有父子关系的情况。但就我而言,这并没有发生。
任何帮助都会非常显着。
我有一个要求,我通过 1 个窗口打开 2 个浏览器窗口。假设 A 打开 B 和 C。然后在其中一个子窗口(比如说 B)中,我打开另一个窗口(比如说 D)。现在,在这个新窗口 (D) 中,我想访问 C 的对象,以检查该窗口是打开还是关闭。
我可以在javascript中做到这一点吗?
我知道您可以通过 use window.open 和 window.opener 但这仅适用于浏览器窗口具有父子关系的情况。但就我而言,这并没有发生。
任何帮助都会非常显着。
是的你可以。假设您的页面 A 像这样打开窗口 B 和 C:
var b = window.open("childB.html", "_blank");
var c = window.open("childC.html", "_blank");
然后您b
的页面窗口childB.html
打开窗口d
var d = window.open("childD.html", "_blank")
在您的javascript代码中childD.html
可以放置代码:
var propC = opener.opener.c.propertyOfC;
opener.opener
将引用原始窗口 A,它可以引用.c
及其所有对象
您将不得不添加对窗口/属性存在的检查(很可能是 try/catch 将按顺序排列)
这是一个使用纯 javascript(又名无库)的工作解决方案。
将此脚本复制到一个新的空白文件中,并为其命名为 window_manager.js
var windows = {};
function openWindow(url, name, features) {
windows[name] = window.open(url, name, features);
return windows[name];
}
function closeWindow(name) {
var window = windows[name];
if(window) {
window.close();
delete windows[name];
}
}
功能 is_window_open(windowName, checkparents){
// check to see if windowName is itself
if(window.name == windowName){
// it's me!
return true;
}
if(checkparents == true){
// check to see if windowName is a direct parent of this window
if (window.opener != null && !window.opener.closed){
// there is an open parent window but is it the one we are looking for?
if(window.opener.name == windowName){
// it's our parent and it is still open
return true;
}
// it's not but let's ask our parent about the window we are looking for
if(opener.is_window_open(windowName, true)){
return true;
}else{
return false;
}
}
}
// check to see if windowName is a direct child of this window
if (windowName in windows){
// this window was opened by this browser but is this window still open?
if(windows[windowName].open && (!windows[windowName].closed)){
// yes this window is open
return true;
}
}
// ask all our children to check their children, etc..
for (var childWindow in windows) {
if (windows.hasOwnProperty(childWindow)) {
// when asking children we dont want them asking the parents, that would be an ugly recursive loop
if(windows[childWindow].is_window_open(windowName, false)){
return true;
}
}
}
// got nobody left to ask
return false;
}
使用
这个函数将递归地向上遍历父链寻找指定窗口名称的存在。在每个级别(甚至它自己),它都会遍历所有的孩子和孩子的孩子等等。寻找指定的窗口名称。最终结果是你会得到一个真(如果命名的窗口是打开的)或假的(窗口关闭或不存在)
我无法复制我创建的用于演示/测试的测试 html 文件的 HTML 代码,因此我将它们放在以下 pastebin 中:pastebin 测试文件代码
使用 pastebin 中给出的代码创建所有 4 个 html 文件:a.htm、b.htm、c.htm 和 d.htm。浏览到 a.htm,它将打开窗口 b 和 c。窗口 b 将打开窗口 d。窗口 d 将检查窗口 c 并返回 True。关闭窗口 c 并刷新窗口 d。它现在将返回 false 因为 c 不再打开