How to set focus to child and opener windows when tabbed

旧街凉风 提交于 2020-01-23 05:56:50

问题


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:

  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.


来源:https://stackoverflow.com/questions/17237542/how-to-set-focus-to-child-and-opener-windows-when-tabbed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!