1

I have a piece of code that launches another page in an external window.

var myOpenWindow = window.open(...);

I manage this window throughout the applications life cycle and once the forum is completed my managing state closes this window.

However, the issue I am facing is that if the user hits f5 for a hard refresh the window is still open after the main page loads.

At first I thought I could override the window.open to track the state of open windows from my app in a global variable. However, I overlooked the fact that on an f5 reset my global is lost.

This seems like a simple problem, but the solution has evaded me. Is there anyway to close a window opened by window.open when the parent is refreshed?

Freddy
  • 2,249
  • 1
  • 22
  • 31

3 Answers3

1
var myOpenWindow = window.open(...);
window.onunload = function(){myOpenWindow.close()};

or better

window.addEventListener('unload',function(){myOpenWindow.close()})

should do that.

MDN: WindowEventHandlers.onunload

myf
  • 9,874
  • 2
  • 37
  • 49
0

Maybe you could use a DIV and place it in the center of the screen. Add some jQueryUI magic and you don't have to worry about popups or blockers or other stuff.

2174714
  • 288
  • 2
  • 10
0

You can keep the window open, with the following code :

When you reload the parent page, the child will change the myOpenWindow when parent page will be loaded.

Parent window :

function detectChild(child) {
    myOpenWindow = child;
    //opener.actionWhenOpen();
}

var myOpenWindow = window.open(...);

window.onunload = function() {
    if (myOpenWindow) {
        myOpenWindow.refreshParent();
    }
};

Child windows :

if (opener) {
    //opener.actionWhenOpen();
    opener.onunload = function() {
        if (opener && opener.myOpenWindow) {
            opener.myOpenWindow.refreshParent();
        }
    };
}

function refreshParent() {
    this.i = ((this.i) ? this.i : 0)+1;
    var i = this.i;
    setTimeout(function() {
        if (!opener) {
            return console.log("Opener closed.");
        } else if (opener.detectChild && !opener.myOpenWindow) {
            this.i = 0;
            opener.detectChild(window);
        } else if (i < 900) {
            console.log("Opener cheked("+i+").");
            refreshParent(i++);
        }
    }, 50);
}
user2226755
  • 12,494
  • 5
  • 50
  • 73