Popup Window Setting Focus

14,896

Solution 1

Just call window.focus() immediately after opening the popup, either in the function or right after it:

<input type="button" value="Open window" onclick="openWin(); window.focus();" />

or

function openWin()
{
myWindow=window.open('','','width=200,height=100');
myWindow.document.write("<p>This is 'myWindow'</p>");
window.focus();
}

Solution 2

Call window.focus() instead of myWindow.focus().


If that's not working, try blurring the window and then re-focusing it:

window.blur();
window.focus();

Solution 3

I was facing the same issue. I found a workaround.

I modified like this:

myWindow.document.write("<p>This is 'myWindow'</p>");
myWindow.document.write("<script>window.opener.focus();</script>");

It worked for me in FF and Chrome.

Share:
14,896
John Doe
Author by

John Doe

Updated on August 20, 2022

Comments

  • John Doe
    John Doe over 1 year

    I have a popup window called myWindow and when it pops up i want the focus to be on the original window, not the popup. I took out the line myWindow.focus();and it still focused on the popup. Does anyone know how to keep the focus on the original window when the popup is created? Live Long and Prosper.

    <!DOCTYPE html>
    <html>
    <head>
    <script type="text/javascript">
    function openWin()
    {
    myWindow=window.open('','','width=200,height=100');
    myWindow.document.write("<p>This is 'myWindow'</p>");
    myWindow.focus();
    }
    </script>
    </head>
    <body>
    
    <input type="button" value="Open window" onclick="openWin()" />
    
    </body>
    </html>
    
  • John Doe
    John Doe almost 12 years
    good idea, but that did not work. im starting to think what i want to do isn't possible...
  • sachleen
    sachleen almost 12 years
    It would make more sense to include that in the function.
  • jeff
    jeff almost 12 years
    @sachleen - Not if he didn't want to set focus back to the main window every time he called openWin(). But I edited my answer to show both ways.
  • jeff
    jeff almost 12 years
    @JohnDoe - What browser are you using? I tested this code, and it's working fine for me in Chrome.
  • John Doe
    John Doe almost 12 years
    ya it worked in IE, it must just not work in MZF..thanks for the help
  • sachleen
    sachleen almost 12 years
    @jeff yeah, but that's how his attempted solution was. :p
  • Sarjith Pullithodi
    Sarjith Pullithodi over 11 years
    or re-write like this myWindow.document.write('<script>window.onload = function () { window.opener.focus() }</script>');