javascript window.focus() 不适用于 Chrome 和 Firefox

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12344204/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 15:59:21  来源:igfitidea点击:

window.focus() not working for Chrome and Firefox

javascriptfirefoxgoogle-chrome

提问by qwertymk

I'm trying to get the window.focus()function to work with no luck.

我正试图让该window.focus()功能在没有运气的情况下工作。

Take a look at this fiddle

看看这个小提琴

var myWindow = window.open('','zzz','width=600,height=700');
    myWindow.document.write('test');
    myWindow.focus();?

If you click run after the jsfiddle page loads then the new window should get back focus. What am I doing wrong?

如果您在 jsfiddle 页面加载后单击运行,则新窗口应该重新获得焦点。我究竟做错了什么?

采纳答案by RobG

It "works" for me in FF 15. Users can disable the ability of scripts to open and focus windows, check your settings. Oh, and the pop–up should get focus by default, so you shouldn't have to call myWindow.focus().

它在 FF 15 中对我“有效”。用户可以禁用脚本打开和聚焦窗口的功能,检查您的设置。哦,默认情况下,弹出窗口应该获得焦点,因此您不必调用myWindow.focus().

Some minor points that probably having nothing to do with the issue but you may want to fix:

一些可能与问题无关但您可能想要解决的小问题:

  1. A valid document should be written to the new window, a title element and one block element are required, e.g. document.write('<title></title><div></div>, a DOCTYPE is highly recommended too
  2. The input stream should be closed after you've finished writing, use document.close()
  1. 一个有效的文档应该写入新窗口,需要一个标题元素和一个块元素,例如document.write('<title></title><div></div>,强烈推荐一个DOCTYPE
  2. 写完后应该关闭输入流,使用 document.close()

回答by enhzflep

For Chrome at least (dont have FF) just replace

至少对于 Chrome(没有 FF)只需替换

myWindow.focus();

with

myWindow.blur();
setTimeout(myWindow.focus, 0);

EDIT: Realized I've got FF in a linux VM. The code is fine with the current Chrome and with FF12 under the newest Mint x64

编辑:意识到我在 linux VM 中有 FF。该代码适用于当前的 Chrome 和最新的 Mint x64 下的 FF12

回答by Burt

This works for me:

这对我有用:

<script> 
var popupWin;
function open_popup(url) {
    if(typeof(popupWin) == "object" ) popupWin.close();

    popupWin =  window.open(url, 'PopupName', 'scrollbars=no,resizable=yes, width=600,height=800,status=no,location=no,toolbar=no'); 
    popupWin.focus();

 }
</script>