javascript alert on parent page when child popup closes
-
27-09-2019 - |
Question
I am using javascript window.open method to open lets say http://www.google.com [its always going to be some external url]
I have stored the reference of the window object in a variable, the problem is that variable never gets null on the parent page and I am not able to alert the user that the pop up has been closed.
Here's the code
var winFB; var winTWt; var counterFB = 0; var counterTWT = 0; var timerFB; function openFB() { if (counterFB == 0) { winFB = window.open("http://www.google.com"); counterFB = 1; } if (counterFB > 0) { alert(winFB); if (winFB == null) { counterFB = 0; clearTimeout(timerFB); alert("Window Closed"); } } timerFB= setTimeout("openFB()", 1000); }
I can not put any javascript code on the pop up/child window.
Hope someone can help me on this
Solution
The window variable doesn't get nulled out when it's closed, however its .closed
property is true
, so just change your check to be for that property, like this:
var winFB;
var winTWt;
var counterFB = 0;
var counterTWT = 0;
var timerFB;
function openFB() {
if (counterFB == 0) {
winFB = window.open("http://www.google.com");
counterFB = 1;
}
if (counterFB > 0) {
if (winFB.closed) {
counterFB = 0;
clearTimeout(timerFB);
alert("Window Closed");
}
}
timerFB = setTimeout(openFB, 1000);
}
Also note the setTimeout()
change, pass a function in whenever possible (almost always) rather than a string, you'll have a lot less problems with scoping.
OTHER TIPS
//in the parent
winFB = window.open("http://www.google.com");
//in the child window you can access
var _parent = window.opener.document;
//also use the onunload event in the child window
onunload="doSomething()"
hope this gives you some direction..