Fight Fire With Fire
Fight Fire With Fire

Reputation: 1686

Can JavaScript detect a popup window when it closes and reopen it?

I have a HTML page that pops open a fullscreen window for an app. What I would like to do is detect when the pop up is closed and reopen it.

var drawingwindow;

function popup(url) 
{
 params  = 'width='+screen.width;
 params += ', height='+screen.height;
 params += ', top=0, left=0'
 params += ', fullscreen=yes';
 params += ', resizeable=no';
 newwin=window.open(url,'drawingwindow', params);
 if (window.focus) {newwin.focus()}
 return false;
}

Then I trigger the pop up from a HTML button

<input type="submit" name="submit" value="Submit" onclick="popup('hello.php')"/>

What I'd like to do is somehow the first page to check on drawingwindow - and if it closes - reopen it immediately. It's part of a drawing app on the main canvas "drawingwindow" and it has a way to close the drawing window permanently.

Upvotes: 0

Views: 267

Answers (1)

Daniel Beck
Daniel Beck

Reputation: 21475

Recent improvements in browser security mean you kind of can't do what you want very well.

You can detect that the popup has closed:

var popupWindow;
var pop = function () {
    popupWindow = window.open("example.html"); // has to be on same domain as original file
    // setting a popupWindow.onclose event doesn't work (it 
    // fires immediately).  You can fake it by observing some 
    // known property of the popup window, such as its location:
    var fakeOncloseEvent = window.setInterval(function () {
        if (!popupWindow.location) {
            // The popup was closed.
            window.clearInterval(fakeOncloseEvent); // tidy up 
            pop(); // <-- But this won't work!
        }
    }, 250);
}

Reopening the popup window will be prevented in most browsers, because you're only allowed to open a new window as a result of direct user action (i.e. a click). (You could use the above to guide the user towards reopening the popup on their own, perhaps by highlighting the "open the popup" link, but you can't open it for them.)

Alternatively you could tackle the problem from the other end, and put code in the popup window to prevent it from closing. But most browsers severely limit what you're allowed to do in an onbeforeunload event -- you're pretty much limited to throwing up a confirm dialog:

window.onbeforeunload = function() {
  // Just return the string, don't return a confirm() here.
  // Various browsers will include their own additional text 
  // in the confirm dialog, and some may ignore your added text altogether.
  return "Are you sure you want to close this beautiful popup?";
}

Upvotes: 1

Related Questions