window.opener
您可以通过链向后扫描:
function getBaseOpener(win){
var opener;
do {
/// check to see if our storage property has been set, if so use it
/// this gets around the problem that the window.opener chain may have
/// been broken.
if ( win.baseOpener ) {
opener = win.baseOpener;
break;
}
/// for each window.opener we find scan backwards until we find a
/// window that has no window.opener. This should be our main window.
} while( (opener = win.opener) && (win = opener) );
/// return the result and store it for next time, this will prevent
/// problems if any of our openers are ever closed.
return (win.baseOpener = opener);
}
上面应该总是返回基本打开器,只要它在每个新打开的窗口上执行一次,就在那个窗口被创建之后(并且整个窗口链在那个时候仍然存在)。
显然,如果基本窗口曾经关闭过,您就会遇到问题;)
更新
抱歉,我认为以上内容很清楚,我想这是因为您已经处理了 Windows 之间的大量相互通信——但如果不是,则不是:) 无论如何,我添加了注释来解释代码并添加了使用信息以使事情更清晰.
放置以下内容,以便将其加载到将要打开的每个窗口中。
<script>
function getBaseOpener(win){
var opener;
do {
if ( win.baseOpener ) {
opener = win.baseOpener;
break;
}
} while( (opener = win.opener) && (win = opener) );
return (win.baseOpener = opener);
}
/// this first execution is important, it creates the baseOpener
/// property that will keep our link to the main window even
/// if our parents have been closed and reopened later on.
var mainWindow = getBaseOpener(window);
</script>
然后,如果您需要获取基本窗口,请在代码中的任何位置使用以下命令:
mainWindow
或再次运行 getBaseOpener:
getBaseOpener(window)
这应该始终返回基本/主窗口(窗口 1) - 除非从基本窗口本身执行......它将返回undefined
。
如果你想使用getElementById
,你需要像这样访问文档:
mainWindow.document.getElementById('element_id');