如何当标签焦点设置到儿童和揭幕战的窗户 [英] How to set focus to child and opener windows when tabbed
问题描述
我如何设置焦点回到父窗口在另一个浏览器选项卡时?我试过:
window.opener.focus();
无济于事。它似乎只在窗户上没有停放工作。
我需要这在Chrome浏览器,IE9 / 10,Firefox和Safari。
Internet Explorer还似乎有问题,将焦点设置到子窗口。例如。使用时:
VAR windowRef = window.open(URL);
然后再从相同的标签:
windowRef.focus(); //在Chrome确定,似乎并不在IE工作...
你到底想实现什么?若要将焦点 其他窗口内设置的第一个链接/按钮/表单字段/什么?或者使其他窗口(浏览器选项卡)活动浏览器标签?
反正 - 也许是 opener.focus()
不能正常工作,因为这两个窗口都没有从同一产地服务。尝试通过<一个建立沟通渠道href=\"http://www.whatwg.org/specs/web-apps/current-work/multipage/web-messaging.html#crossDocumentMessages\"相对=nofollow> postMessage的来解决这个问题。因此,揭幕战
文件中,听着像这样一个事件:
window.addEventListener('消息',函数(事件){
window.focus()的;
},FALSE);
而在打开的窗口中发送的消息是这样的:
opener.postMessage('富','*');
不幸的是,如果这是工作,现在我无法测试。 (我猜它应该,虽然...)
有几件事情加,虽然:
- 某些旧的废话浏览器不支持的postMessage(见 caniuse.com )。有解决方法,虽然。 :)
- 我用了W3标准符号用于连接事件侦听器。 IE8及以下使用其专有的
的attachEvent
等价的。 - 您应该与首战窗口的确切起源替换
'*'
起源通配符。 - 在消息事件侦听器功能,您应检查event.origin,只运行实际的有效负载,如果原产地是正确的。
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...
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
attachEvent
equivalent. - 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.
这篇关于如何当标签焦点设置到儿童和揭幕战的窗户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!