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

时间:2014-08-07 07:56:10

标签: javascript jquery jquery-cookie

我有一个页面(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被重新初始化。

为了解决这个问题,我使用了cookies,但它没有用。我在下面的代码中遗漏/做错了什么?

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

1 个答案:

答案 0 :(得分:1)

正如您已经想到的那样,变量在运行进程之外不存在。因此,您无法将其保存在例如饼干。

显而易见的方法是跟踪窗口名称:

  

var windowObjectReference = window.open(strUrl, strWindowName [,strWindowFeatures]);

这些是字符串,因此可以存储在任何地方。但是,某些浏览器(即Chrome)会在独立线程中打开选项卡,这意味着一旦关闭父窗口,子窗口就会无法访问。

我认为你可以尝试反过来这样做:

  • 为每个子窗口分配唯一ID
  • 商店ID(本地存储,Cookie,等等)
  • 按ID对每个子窗口进行轮询,直到他们收到工作