window.open创建对基于名称的引用

时间:2010-07-08 18:03:20

标签: javascript

这样我得到了对打开窗口的引用:

var refWin = window.open("mypage1", "name_mypage");

如果你想关闭窗口,我关闭:

refWin.close();

如果我进行屏幕刷新(F5)并运行相同的行,它将在同一窗口中打开,因为我使用相同的名称。

var refWin = window.open("mypage2", "name_mypage");

但有不同的引用(refWin)。

问题:如何根据名称引用窗口?我需要在打开前关闭窗口,名称相同。

做类似的事情:

var refWin = window.open("about:blank", "name_mypage");
refWin.close();
refWin = window.open("mypage2", "name_mypage");

但不必是一个空白窗口供参考。

感谢

2 个答案:

答案 0 :(得分:0)

根据andres的评论,这是他正在寻找的解决方案:

refWin.location = "myurl";
refWin.focus();

这将在窗口中打开“myurl”并将其聚焦。

或者

var refWin = window.open("mypage1", "name_mypage");
refWin.focus();

修改

如果您没有再次重新加载页面,则不应该有任何理由不能这样做:

var refWin = window.open("mypage1", "name_mypage");
refWin.close();
refWin = window.open("mypage1", "name_mypage");

如果你真的很担心,你可以制作自己的“windows”对象:

var windows = {};
var refWin = window.open("mypage1", "name_mypage");
windows[refWin.name] = refWin;
windows("name_mypage").close();  // close the window

我认为这不是很有效率,因为你仍然无法可靠地关注它,但也许它适合你的用途。

答案 1 :(得分:0)

我的解决方案基于另一个脚本:

Helper.window = new function () {

    // Private fields
    var w = window, s = screen, _self = this, whs = {}, isChrome = /chrome/.test(navigator.userAgent.toLowerCase());

    // Public Members
    this.focus = function (wh) {
        if (!wh) return;
        if (isChrome) wh.blur();
        wh.focus();
    };

    this.windowExists = function (wt) {
        return wt && whs[wt] && (typeof whs[wt]['closed'] != undefined) && !whs[wt].closed;
    };

    this.close = function (wt) {

        if (typeof whs[wt][close] != undefined) whs[wt].close();
        whs[wt] = null;

        return _self;
    };

    this.properties = function (wp) {

        wp = (wp || 'menubar=yes').toLowerCase();

        if (!(/menubar/.test(wp)))
            wp += 'menubar=yes';

        if (!(/location/.test(wp)))
            wp += ',location=yes';

        if (!(/width/.test(wp)))
            wp += ',width=' + (s.availWidth - 150);

        if (!(/height/.test(wp)))
            wp += ',height=' + (s.availHeight - 150);

        if (!(/scrollbars/.test(wp)))
            wp += ',scrollbars=yes';

        if (!(/resizable/.test(wp)))
            wp += ',resizable=yes';

        return wp;
    };

    this.open = function (url, wt, wp) {

        if (_self.windowExists(wt))
            return _self.close(wt).open(url, wt, wp);

        var urlOpen = '';
        if (typeof url == 'string') {
            urlOpen = url;
        } else if (jQuery(url).get(0).tagName.toLowerCase() == 'a') {
            urlOpen = jQuery(url).attr('href');
        } else {
            urlOpen = 'about:blank';
        }

        wp = _self.properties(wp);
        wt = wt || "_blank";

        var wh = wp ? w.open(urlOpen, wt, wp) : w.open(urlOpen, wt);

        if (wh && "_blank" !== wt) {
            whs[wt] = wh;
            _self.focus(wh);
        }

        return wh;
    };

};