父窗口的跨域window.close事件 [英] Cross-domain window.close event from parent window

查看:81
本文介绍了父窗口的跨域window.close事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我在domain1上:

For example I'm on domain1:

a.click(function(){
  window.win=window.open(domain2,'name');
});

现在我在domain2上并且正在关闭它. window.win 如何知道用户关闭了该窗口?是否有任何事件或属性可以通过时间间隔检查?

Now I'm on domain2 and I'm closing it. How will window.win know that user closed that window? Is there any event or property to check via interval?

推荐答案

有一个属性不属于任何W3C规范.它被称为 closed ,并且会像

There is a property which is not part of any W3C spec. It's called closed and would get accessed like

if( window.win.closed ) {
    // window was closed
}

我不确定该属性的跨浏览器兼容性.我也不确定跨域域的行为.但是,如果您尝试使用它,请让我和其他社区成员了解它.

I'm not sure about the cross-browser compatibilty for that property. I'm also not sure how this behaves on cross-origin domains. But if you try it please let me and the rest of this community know about it.

另一个选择是您自己处理通知.这意味着,您正在监听弹出窗口中的 onbeforeunload .事件触发时,您可以使用HTML5的 postMessage 方法在跨域窗口之间进行通信.例如:

Another option is that you take care for the notification yourself. That means, you are listening for the onbeforeunload within the popup-window. When the event fires, you could use HTML5's postMessage method to communicate between cross-domain windows. For instance:

MainWindow:

MainWindow:

window.addEventListener('message', function(e) {
    if( e.origin === 'http://www.popupdomain.com' ) {
        if( e.data === 'closed' ) {
            alert('popup window was closed');
        }
    }
}, false);

Domain2:

window.onbeforeunload = function() {
    window.opener.postMessage('closed', 'http://www.popupdomain.com');
};

此解决方案的唯一警告是,它仅与支持基本HTML5的浏览器兼容.在老式的浏览器上还有其他(鬼s)的跨域通信方式,但是我想那是另一回事了.

The only caveat on this solution is that it's only compatible with browser that support basic HTML5. There are other (sneaky) ways to have a cross-domain communication on old'ish browsers, but I guess that is another story.

这篇关于父窗口的跨域window.close事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆