Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set focus to child and opener windows when tabbed

How do I set focus back to the parent window when in another browser tab? I've tried:

window.opener.focus();

to no avail. It only seems to work when the windows are not docked.

I need this to work in Chrome, IE9/10, Firefox, and Safari.

Internet Explorer also seems to have issues setting focus to a child window. E.g. when using:

var windowRef = window.open(url);

then later from the same tab:

windowRef.focus(); // ok in Chrome, doesn't seem to work in IE...
like image 766
magritte Avatar asked Jun 21 '13 14:06

magritte


People also ask

How to focus parent window from child window in javascript?

focus() method. Your child window can refer to its parent window with 'opener' - so the command in the child window would be opener. focus(), or window. opener.

What is window opener?

opener. The Window interface's opener property returns a reference to the window that opened the window, either with open() , or by navigating a link with a target attribute. In other words, if window A opens window B , B. opener returns A .

What is window focus in Javascript?

focus() Makes a request to bring the window to the front.


1 Answers

What exactly do you want to achieve? To set the focus inside the other window to the first link / button / form field / whatever? Or to make the other window (browser tab) the active browser tab?

Anyways - maybe the opener.focus() call doesn't work because both windows are not served from the same origin. Try setting up a communication channel via postMessage to resolve this. So in the opener document, listen for an event like this:

window.addEventListener('message', function (event) {
    window.focus();
}, false);

And in the opened window, send the message like this:

opener.postMessage('foo', '*');

Sadly, I can't test if this is working right now. (I guess it should, though...)

A few things to add, though:

  1. Some legacy crap browsers don't support postMessage (see caniuse.com). There are workarounds, though. :)
  2. I used the W3 standard notation for attaching the event listener. IE8 and below use their proprietary attachEvent equivalent.
  3. You should replace the '*' origin wildcard with the actual origin of the opener window.
  4. In the message event listener function, you should inspect event.origin and only run your actual payload if the origin is correct.
like image 173
defaude Avatar answered Oct 07 '22 13:10

defaude