views:

190

answers:

3

Hello All, I am creating a pop up window. After I am finished with the work on child(pop up) window and click close button, i need to call a javascript function of the parent window. How can I achieve this. I am not creating the child window myself but displaying the contents of some other url.

A: 

If the child window is not originating from the same domain name as the parent window, you're locked out due to the same origin policy. This is done deliberately to prevent cross-site-scripting attacks (XSS).

Diodeus
thanks for the info
biluriuday
+4  A: 

I don't think you can get an event, because you can't mess with the document itself when the URL is from a different domain. You can however poll and check the "closed" property of the window object:

var w = window.open("http://what.ever.com", "OtherWindow");
setTimeout(function() {
  if (w.closed) {
    // code that you want to run when window closes
  }
  else
    setTimeout(arguments.callee, 100);
}, 100);

You could also start an interval timer if you prefer:

var w = window.open("http://what.ever.com", "OtherWindow");
var interval = setInterval(function() {
  if (w.closed) {
    // do stuff
    cancelInterval(interval);
  }
}, 100);
Pointy
sorry for my ignorance, but what does the setTimeout(arguments.callee, 100); does? to make the timeout recursive?
biluriuday
The "arguments.callee" variable is a reference to the function being called. So, yes, it sort-of makes it recursive, except it's not really recursive because it's not the function calling itself but rather the Javascript runtime calling the function again, after another timeout. You could also set this up with an setInterval; I'll type in an example.
Pointy
+1. @Pointy, I posted an answer that uses a named closure for the timeout recursive(ish) function to avoid the use of arguments.callee. I'll vote to delete my post if you update yours. :-)
David Murdoch
thanks @Pointy and @David Murdoch
biluriuday
A: 

Don't vote for this. It is just an improvement of Pointy's code to getting rid of arguments.callee. Vote for Pointy.

var w = window.open("http://what.ever.com", "OtherWindow");
setTimeout(function timeout() {
  if (w.closed) {
    // code that you want to run when window closes
  }
  else
    setTimeout(timeout, 100);
}, 100);
David Murdoch
Well it's true that you can name your functions like that, but it's problematic: http://yura.thinkweb2.com/named-function-expressions/ - I really wish it would work properly however, and the lack of this facility in Erlang really, really bugs me!
Pointy
I don't think this will cause the issues you think it will cause. "timeout" will ONLY be accessible from within the "timeout" function's scope. It is equivalent to the anonymous function: `function(){var timeout = arguments.callee;}`
David Murdoch
Hm, it seems that `setTimeout(function fnName(){}, n)` will apparently fail in Safari 2.x (which is 5 years old now and pretty irrelevant, IMO).
David Murdoch