简体   繁体   中英

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.

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(); };

window does not have the onblur event

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

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 .

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