How to run function of parent window when child window closes?
I am calling the javascript window.open() function to load another url in a pop up. Once the users is finished it takes them to the last page that has a link that says close window that calls the window.close() function. Now when that page closes I need to update something in the original page that opened the window. Is there any way to do this? I have to call a function that is in my original page.
You can somehow try this:
Spawned window:
window.onunload = function (e) {
opener.somefunction(); //or
opener.document.getElementById('someid').innerHTML = 'update content of parent window';
};
Parent Window:
window.open('Spawn.htm','');
window.somefunction = function(){
}
You should not do this on the parent, otherwise opener.somefunction() will not work, doing window.somefunction makes somefunction as public:
function somefunction(){
}
You probably want to use the 'onbeforeunload' event. It will allow you call a function in the parent window from the child immediately before the child window closes.
So probably something like this:
window.onbeforeunload = function (e) {
window.parent.functonToCallBeforeThisWindowCloses();
};
This is an old post, but I thought I would add another method to do this:
var win = window.open("http://www.google.com");
var winClosed = setInterval(function () {
if (win.closed) {
clearInterval(winClosed);
foo(); //Call your function here
}
}, 250);
You don't have to modify the contents or use any event handlers from the child window.
The answers as they are require you to add code to the spawned window. That is unnecessary coupling.
// In parent window
var pop = open(url);
pop.onunload = function() {
// Run your code, the popup window is unloading
// Beware though, this will also fire if the user navigates to a different
// page within thepopup. If you need to support that, you will have to play around
// with pop.closed and setTimeouts
}