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

查看:393
本文介绍了Javascript:跨域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 does window.win will know that user closed that window? Is there any event or property to check via interval?

推荐答案

有一个属性不属于任何W3C规范。它被称为关闭,将像

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的浏览器。还有其他(鬼鬼祟祟)的方式可以在旧的浏览器上进行跨域通信,但我想这是另一个故事。

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.

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

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