javascript:父窗口如何知道其子窗口已关闭?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5240428/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 16:29:14  来源:igfitidea点击:

javascript: How Can a parent window know that its child window closed?

javascriptjavascript-eventsyui

提问by Vin

I want to execute a function when an opened child window is closed. Child window opening code is:

我想在打开的子窗口关闭时执行一个函数。子窗口开启代码为:

outWin = window.open (pageURL, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=no, copyhistory=no, width=600, height=400, top=100, left=100);

i want to call a javascript function written in parent window.I am using YUI-2 for developing the plugin. How can i make it work? what event should be registered?

我想调用在父窗口中编写的 javascript 函数。我正在使用 YUI-2 来开发插件。我怎样才能让它工作?应该注册什么事件?

thanks in advance.

提前致谢。

回答by Mark Coleman

You could do something like this.

你可以做这样的事情。

var intervalID, childWindow;

childWindow = window.open("http://www.google.com");

function checkWindow() {
    if (childWindow && childWindow.closed) {
        window.clearInterval(intervalID);
        alert('closed');
    }
}
var intervalID = window.setInterval(checkWindow, 500);

References: window.setIntervaland this answer.

参考资料:window.setInterval和这个答案

Simple example on jsfiddle.

jsfiddle上的简单示例。

回答by JeanK

You can try acces the parent window by:

您可以通过以下方式尝试访问父窗口:

window.opener.functionThatYouWant();

This code is inside de child window.

此代码位于子窗口内。

But if you open an window that the URL is in another domain (not localhost), you can't access it because of security issues.

但是,如果您打开一个窗口,表明该 URL 位于另一个域(不是 localhost)中,则由于安全问题,您将无法访问它。

I used this code on Firefox, I am not sure if it works crossbrowser.

我在 Firefox 上使用了这段代码,我不确定它是否适用于跨浏览器。