简体   繁体   English

当它失去焦点时关闭弹出窗口

[英]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. 我想知道是否可以使用javascript创建一个弹出窗口,然后在它失去焦点时关闭该窗口。

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? 弹出窗口的URL是否与父对象的域相同? If not, you will likely not be able to attach an event to the new window's onblur event. 如果没有,您可能无法将事件附加到新窗口的onblur事件。

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: 在查看StackOverflow时从浏览器控制台运行此命令,以确保当弹出窗口与原始窗口位于同一域时,它确实有效:

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

window does not have the onblur event window没有onblur事件

Try to call it's closing by focusing on the <body> of the main window 尝试通过关注主窗口的<body>来调用它

The problem you may be having is that you are binding the onblur handler before the window has begun loading the page. 您可能遇到的问题是您在窗口开始加载页面之前绑定了onblur处理程序。 Once the page is loaded, your onblur handler is gone. 加载页面后,您的onblur处理程序就会消失。 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. 如果要在其他域中加载页面,则根本无法绑定onblur处理程序。 You'll need to stick to your solution using onfocus . 你需要使用onfocus坚持你的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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