最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - window.focus() not working for Chrome and Firefox - Stack Overflow

programmeradmin1浏览0评论

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

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?

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

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?

Share Improve this question edited Sep 10, 2012 at 2:43 Charles 51.5k13 gold badges106 silver badges144 bronze badges asked Sep 10, 2012 at 0:47 qwertymkqwertymk 35.4k30 gold badges124 silver badges184 bronze badges 10
  • 1 It's working for me in Chrome. – The Alpha Commented Sep 10, 2012 at 1:03
  • @SheikhHeera Are you on Chrome 21? – qwertymk Commented Sep 10, 2012 at 1:05
  • @SheikhHeera I turned off all my extensions and it's still not working for me – qwertymk Commented Sep 10, 2012 at 1:08
  • Don't you see the window at the top and Focused! inside it ? – The Alpha Commented Sep 10, 2012 at 1:09
  • @SheikhHeera yes, the first time, but when I click run again, it doesn't refocus – qwertymk Commented Sep 10, 2012 at 1:10
 |  Show 5 more ments

3 Answers 3

Reset to default 1

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().

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 remended too
  2. The input stream should be closed after you've finished writing, use document.close()

For Chrome at least (dont have FF) just replace

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

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>
发布评论

评论列表(0)

  1. 暂无评论