简体   繁体   中英

javascript closing a window from another window overwrites calling window name

I have a website opening several new tabs/windows. On the main page of the website, there's a button 'close all', which should close all windows opened from the website. At first sight, it seems to work fine. However, the name of the main page is overwritten by the last page that was opened when pressing the 'close all'-link. The result of this is that, whenever that last opened page is called again, it is not opened in a new tab, but in the main page-tab (which is clearly not what I want).

See this mwe:

popupmanager.js:

function PopupManager() {
    this.name = "_popupmanager_";
    this.windows = {};
};

PopupManager.prototype.open = function(url, name) {
    this.windows[name] = window.open(url, name);
    this.windows[name].focus();
};

PopupManager.prototype.closeAll = function() {
    for (name in this.windows) {
        this.closeWindow(name);
    }
};

PopupManager.prototype.closeWindow = function(name) {
    if (this.windows[name]) {
        this.windows[name].close();
        delete this.windows[name];
    }
};

main page being index.html:

<!doctype html>

<html>
<head>
    <script src="./popupmanager.js"></script>
    <script>
        var popupManager = new PopupManager();
    </script>
</head>
<body>
    <ul>
        <li><a href="javascript:popupManager.open('http://www.facebook.be', 'facebook')">facebook</a></li>
        <li><a href="javascript:popupManager.open('http://www.google.be', 'google')">google</a></li>
        <li><a href="javascript:popupManager.closeAll()">close all/a></li>
    </ul>
</body>
</html>

Now, when you click on the first link, than the second, both pages are opened. If you press 'close all', everything seems to work fine. However, at this point, the main page-tab has name 'google' (as a result of the execution of the function 'closeAll'). If you click the second link again, it is opened in the main page, not in a new tab. I see this behaviour in Firefox 21.0, Google Chrome 24.0.1312.60m, and IE9, so I suppose it's the intended behaviour of javascript.

I just don't see why the name of the main page is overwritten and/or how to make the script not to overwrite the name of the main page-tab. Anyone?

Allright, I managed to solve it myself. I've been doing some fine-tuning of the 'closeWindow'-function and this did the trick:

PopupManager.prototype.closeWindow = function(name) {
    if (this.windows[name]) {
        if (!this.windows[name].closed) {
            this.windows[name].opener.name="indexpage";
            this.windows[name].close();
        }
        delete this.windows[name];
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM