Thursday 24 March 2011

Javascript: Get topmost parent window in series of nested child windows.

Hi,
Suppose you have opened a pop up window using window.open which in turn opens a new popup window and so on.
For Ex: Parent > Child1 > Child2 > Child3 > ...
Here, > indicates relationship Parent Window > Child Window

Now suppose you want topmost parent window (Parent) from any child window (say, Child3) then you can get this using below function:

Insert this code in your Child3 page:

<script type="text/javascript" language="javascript">

function getTopMostParentWindow() {
           var win = window;
           var topWindow = null;
           while (win = win.opener) {
                topWindow = win;
            }
            return topWindow;
 }


</script>

Now this method will return top most parent window if exists, else null.

3 comments:

  1. Can u pls mention ur browser type n version

    ReplyDelete
  2. Suppose if user close the child2 window , how to find parent window from then child 3 ( child3 opened from child2)

    ReplyDelete