James W.
James W.

Reputation: 19

Closing a pop up window when it loses focus

I am wondering if it is possible to create a pop up window with javascript, and then close that window when it loses focus.

Here is my code:

    var theWindow;


function launchWindow() {
            theWindow=window.open('www.domain.com');

          theWindow.onblur = function() {
                this.close();
        };
}

But that doesn't work at all. Any suggestions?

EDIT: I have discovered a solution that works for me, hopefully it will work for someone else:

var theWindow;
var windows = [];


function launchWindow() {
            theWindow=window.open('www.domain.com');

            windows.push(theWindow);

            window.onfocus = function() {
                for (x in windows) {
                    windows[x].close();
                }
            };
}

It's not an exact solution to my original problem (It doesn't close the window when it loses focus, but rather it closes it when the main window regains focus) but it works for me.

Upvotes: 0

Views: 7631

Answers (3)

gilly3
gilly3

Reputation: 91707

The problem you may be having is that you are binding the onblur handler before the window has begun loading the page. Once the page is loaded, your onblur handler is gone. You'll need to defer binding long enough to give the page a chance to start loading before binding your event handler:

function launchWindow() { 
    var theWindow = window.open('www.domain.com'); 
    setTimeout(function() {
        theWindow.onblur = function() { 
            this.close();
        };
    }, 2000); 
} 

If you are loading a page in a different domain, you won't be able to bind the onblur handler at all. You'll need to stick to your solution using onfocus.

Upvotes: 0

RoccoC5
RoccoC5

Reputation: 4213

Is the URL of the popup window from the same domain as the parent? If not, you will likely not be able to attach an event to the new window's onblur event.

Run this from your browser console while viewing StackOverflow to see that it does in fact work when the popup is on the same domain as the originating window:

var theWindow = window.open ("http://www.stackoverflow.com","theWindow");
theWindow.onblur = function() { this.close(); };

Upvotes: 2

Michael Sazonov
Michael Sazonov

Reputation: 1533

window does not have the onblur event

Try to call it's closing by focusing on the <body> of the main window

Upvotes: 0

Related Questions