Introduction
In this article we are going to discuss something on the parent-child behavior of JavaScript.
Description
To understand more on the parent-child relationship let's take an example. I have a browser window and inside that I am clicking on a link. This link will open up a child window and inside that I have more links. Some link(s) that are available inside the child window will open the pages in new window(s). Now if this keeps on growing and from the first browser window (parent) we will end up with some 'n' number of child-subchild relationships. Question is that from the nth child window I would like to open one link inside the parent (first browser) window. How are you going to achieve this?
We will discuss the same in the following code block:
if(typeof(window.opener)!="undefined")
{
var x_win = window.self;
while(x_win!="undefined")
{
x_win = x_win.opener;
if(typeof(x_win.opener)=="undefined")
{
x_win.location.href="http://www.thecodeproject.com/";
break;
}
}
}
else
{
window.location.href="http://www.thecodeproject.com/";
}
In the first line of code (typeof(window.opener)!="undefined")
we are checking whether the window has a parent window? If yes, after this I am declaring a variable x_win
and giving the reference of the current window by using window.self
. As we wanted to achieve the functionality of opening a link of child or subchild window in parent, we go through a while(x_win!="undefined")
loop which ensures that I land myself at the right place. Inside the while
loop, I am assigning the variable x_win = x_win.opener
to ensure that now the child or the subchild window points to its parent and at the moment I am at the parent and so, I have to check for a condition typeof(x_win.opener)=="undefined"
. Whenever I succeed in that condition it means that I am set to change the main page's layout or anything that you want to do.
Everything is simplified as of now while explaining about the parent-child relationship. Let me ask you one question: What will happen if I close the child 'x' window out of 'n' number of child windows? Well, you are right it will throw an exception which is necessary to handle. So, after changing the above code with some exception handling, it will look like this:
try
{
if(typeof(window.opener)!="undefined")
{
var x_win = window.self;
while(x_win!="undefined")
{
x_win = x_win.opener;
if(typeof(x_win.opener)=="undefined")
{
x_win.location.href="http://www.thecodeproject.com/";
break;
}
}
}
else
{
window.location.href="http://www.thecodeproject.com/";
}
}
catch(e)
{
window.open("/");
}
Happy coding...