Thursday, September 5, 2013

JavaScript close child window without closing parent

When using Javascript to close a child window used say as a pop-up window from an asp.net page, one of the issues we may run into is while trying to close the child window using a html input button/link etc.

Using window.close() would try to close not just the child window but the parent as well, along with the accompanying IE alert dialog that ask you that the current window is trying to close all the windows.

One way to get around this issue is by assigning the self property to the child window as shown below. That way when it calls the close() routine, Javascript understands it wants to close itself - this is the classic example of the "this" Javascript conundrum.

function OpenPopup()
{
   window.open('url','name','options');
   window.opener = self;
   window.close();
}


Another technique I have used when using an asp.net hyperlink control to open a child window from within a grid is to

  • set the hyperlink target to null
  • use javascript:void(...)
  • give an empty string for the name parameter and then
  • call self.close() from the child window

Example in the code behind routine for NavigateUrl of the parent window that has the grid and hyperlink -

hlnk.Target = null;
return "javascript:void(window.open('childPopup.aspx?track=" + trackNumber + "','','height=500,width=800, left='+((screen.width - 800) / 2)+', top='+((screen.height - 500) / 2)+', toolbar=no,menubar=no,status=no,scrollbars=yes,resizable=no'))";

Notice the use of the special syntax for top and left to center the child window in the middle of the screen.
This is so that Javascript evaluates the math operation and use that to assign it as the left and top key values.Otherwise Javascript won't evaluate the expression if used simply as left=(screen.width - 800)/2, and simply assign (screen.width - 800)/2 as a string!!