Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

javascript - How to run function of parent window when child window closes?

I have asked this question before and the problem was half solved in the sense I was helped to find out that Javascript has some tough security in place.

What I learnt: A parent Window opens a child window. The child window redirects to a different domain and gets redirected back. It attempts to fire off a function of the parent window upon closing itself.

window.opener.startLoad();

This leads to a permissions (security) problem and will not work.

(Half) New Problem: How can I get a window to open a child window and when it closes run a function in the parent window?

I need a very efficient way of doing this as this will be happening a lot!

Thank you for any help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this:

var win = window.open(url, name);
win.onunload = afterChildClose; // afterChildClose() is the function.
win.close(); // afterChildClose() should fire now.

All this code would be located and executed in the parent window's javascript (including afterChildClose()). You are creating the window and assigning the function to the unload event.

Oh, one thing I just thought of. If the child window refreshes or navigates to another url, the onunload event will fire as well. If you only want the event to fire when the window is closed, you should include a check in afterChildClose() on win.closed.

EDIT: Here is the code to two sample pages I put together to try this out.

Parent window:

<html>
<body>
<script type="text/javascript">
    var win = window.open("secondwindow.html", "woo");
    win.onunload =onun; 

    function onun() {
        if(win.location != "about:blank") // This is so that the function 
                                          // doesn't do anything when the 
                                          // window is first opened.
        {
            alert("closed");
        }
    }
</script>
</body>
</html>

child window ("secondwindow.html"):

<html>
<body>
<script type="text/javascript">
    setTimeout('window.close();', 5000);
</script>
</body>
</html>

When I try opening the first document in firefox, it opens the window, the window waits 5 seconds and quits, and the first document shows the alert(), so it is working even when the sub window closes itself.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...