问题
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...
回答1:
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:
- Some legacy crap browsers don't support postMessage (see caniuse.com). There are workarounds, though. :)
- I used the W3 standard notation for attaching the event listener. IE8 and below use their proprietary
attachEventequivalent. - You should replace the
'*'origin wildcard with the actual origin of the opener window. - In the message event listener function, you should inspect event.origin and only run your actual payload if the origin is correct.
来源:https://stackoverflow.com/questions/17237542/how-to-set-focus-to-child-and-opener-windows-when-tabbed