如果父窗口刷新,检索对子窗口的引用

Retrieving references to child window if the parent refreshes

本文关键字:窗口 引用 刷新 如果 检索      更新时间:2023-09-26

我有一个页面(parent.html),其中有许多链接,点击打开一个窗口:

winRef = window.open(url, '_blank', 'width=800,height=600,resizable,scrollbars');

要在子窗口关闭时给出警告,我在parent.html中使用以下命令:

var timer = setInterval(function() {   
        if(win_ref.closed) {  
            clearInterval(timer);  
            alert("window closed");
            console.log("name is"+name);
            list.remove(name);  
        }  
}, 1000);

这很好。如果子窗口被关闭,则警告用户。但是如果父窗口被刷新,那么它不会警告用户,原因是在这种情况下winRef被重新初始化。

为了解决这个问题,我使用了cookie,但它不起作用。我错过了什么/做错了下面的代码?

var winRef;
var list = new cookieList("cookie_for_winRef");
var list_items = [];
var win_refs = new cookieList("winrefs");
var win_refs_items = [];
var index;
list_items = list.items();
function open_online_editor(name) {
    index = list_items.indexOf(name);
    if (index > -1) {
        //list.remove(name);
        alert("Window is already opened");
        return;
    }
    var url = '$action?command=dbot_show_online_editor&name='+name;
    if (typeof (winRef) == 'undefined' || winRef.closed) {
            //create new, since none is open
            console.log("in if");
            winRef = window.open(url, '_blank', 'width=800,height=600,resizable,scrollbars');
    }
    else {
            try {
                winRef.document; //if this throws an exception then we have no access to the child window - probably domain change so we open a new window
            }
            catch (e) {
                winRef = window.open(url, 'width=800,height=600,resizable,scrollbars');
            }
            //IE doesn't allow focus, so I close it and open a new one
            if (navigator.appName == 'Microsoft Internet Explorer') {
                winRef.close();
                winRef = window.open(url, 'width=800,height=600,resizable,scrollbars');
            }
            else {
                //give it focus for a better user experience
                winRef.focus();
            }
        }
        list.add(name);
        win_refs.add(winRef);
        win_refs_items = win_refs.items();
        var length = win_refs_items.length;
        for(var count=0;count<length;count++){
        var timer = setInterval(function() {   
        if(win_refs_items[count].closed) {  
            clearInterval(timer);  
            alert("closed");
            list.remove(name);  
        }  
        }, 1000);
        }
}

我用于cookie处理(添加/删除/清除/项)的函数是:http://pastebin.com/raw.php?i=647fGSJv

正如您已经发现的,变量不存在于运行的进程之外。因此,您不能将它们保存在例如cookies中。

最明显的方法是跟踪窗口名称:

var windowObjectReference =窗口。open(strUrl, strWindowName[, strWindowFeatures]);

这些都是字符串,所以可以存储在任何地方。然而,一些浏览器(如Chrome)在独立的线程中打开选项卡,这意味着一旦关闭父窗口,子窗口将无法访问。

我想你可以试着用另一种方式来做:

  • 为每个子窗口分配一个唯一的ID
  • 存储id(本地存储,cookie,等等)
  • 让每个子窗口按ID轮询,直到它们收到一个任务