Is it possible for parent window to notice if child window has been closed?

丶灬走出姿态 提交于 2019-12-07 01:19:54

问题


I have parent window (opener) and child (popup)

----------                      --------------
|         |                     |            |
| parent  | -----> opens popup  |  child     |
|         |                     |            |
-----------                     --------------

Let's say, in parent page, I have js function hello()

In order for child to call parent's hello() when the child window is closed and also pass an argument, I can do,

window.close();
window.opener.hello(someArgument);

This will close the window and also call parent's hello();

But what if I don't want to have the code window.opener.hello() in child page? I mean I want the code to be in parent page only

One thing I can think of is:

Somewhat parent knows when the child is closed (event listenr??? not sure in js) But in such case how to receive the argument? (i.e. some data back from the child)


回答1:


The obvious solution (adding an onunload event handler property to the pop-up window object) won't work in IE. However, using attachEvent does work in IE, so the following will do the job:

var win = window.open("popup.html");

function doStuffOnUnload() {
    alert("Unloaded!");
}

if (typeof win.attachEvent != "undefined") {
    win.attachEvent("onunload", doStuffOnUnload);
} else if (typeof win.addEventListener != "undefined") {
    win.addEventListener("unload", doStuffOnUnload, false);
}

If you want the pop-up window to pass information to the main window, I'd suggest placing a property in the pop-up's window object (e.g. window.someValue = 5;). In doStuffOnUnload(), you can then pick up on that property: alert(win.someValue);




回答2:


you could attach an onunload event to the child window from the parent



来源:https://stackoverflow.com/questions/4709400/is-it-possible-for-parent-window-to-notice-if-child-window-has-been-closed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!