Search code examples
javascriptwindow.open

Maintaining a specific window hierarchy in javascript


so i am writing some javascript to handle multiple windows and i need a way to enforce the following hierarchy: the main window should be parent to all other windows opened, regardless of where those other windows were opened from. ie. if the main window opens a child using window.open(), and the child opens a window using window.open(), these two child windows need to be siblings and children of the main window, currently one child is parent to the other and this is causing problems. is there any way to refer to the parent window before calling window.open() so the parent is set as the parent of the new window, instead of the window the javascript function is called from?

i tried this without success, but it may be close:

if (window.opener && !window.opener.closed) {
  window.opener.functionThatEventuallyOpensAWindow();
} else {
  functionThatEventuallyOpensAWindow();
}

if anyone has any ideas it would be greatly appreciated. please note that this code segment can not directly use window.open(), but must call other functions which eventually end in a window.open().


Solution

  • Found the fix. I needed to follow the function calls down to the actual window.open and add to some logic to detect if i was in a child and, if i was, call window.opener.open() instead. not sure why it was not able to change context earlier in the call stack, but it works :)