Javascript return focus to parent tab

Javascript return focus to parent tab

This one took me a bit. I was creating a new tab on form submission. If a user clicks a button on the new tab, focus had to be shifted back to the parent tab. If the form was submitted again the child tab is deleted and replaced by a new child tab. Makes for a handy query and review results then modify query scenario but in separate tabs. The trick was in returning focus to the parent. One would think this would be possible with window.opener.focus(). But modern browsers don’t allow this because you can manipulate the users tabs. The work around is to name the parent window then use

window.open('','parent')

it to reset the tab focus.

Tested in chrome, but this trick doesn’t work in FF or IE. Hope this helps someone else.

Parent

//markup

//js

 
<script>
 
// <![CDATA[
var i = 0;
var windows = [];
window.name = 'parent';
 
//handle child birth		  
function announceWindow(win){
   //if there is already a window open, close it and save ref to new one
   if(i==1){   
       windows[0].close();
       delete windows[0];
       i = 0;	
   }
   //store a reference to the window
   windows[i] = win;
   i++;
}
// ]]>
 
</script>

child tab
//markup for button that takes you pack to parent

<input type="button" />

//js

<script>
// <![CDATA[
      //tell that parent that the child is born! so it can keep track of them and get rid of them as needed.
      if (window.opener) {
      	window.opener.announceWindow( window );
      }
      //set the focus back to the parent window
      function focusParentWindow(){
        window.open('','parent').focus();
      }
// ]]>
</script>
This entry was posted in Uncategorized. Bookmark the permalink.