Skip to content
Advertisement

How can I focus() to another window on javascript, when the page loads?

The new question

On Google Chrome, I can only focus() windows if an element has been clicked.

The original question

How can I focus() to a window using javascript, of which the popup window wasn’t created inside the same window I’m using to focus the webpage

var wnd = window.open("http://bing.co.uk", "stage");

Works fine for modifying popup windows that have been opened from a different webpage.

wnd.focus();

However this does not work as the stage window was already open, when the webpage with the wnd focus function was open.

Advertisement

Answer

Answer to your original question:

If you know that a window with that name exists, you can get a reference to it from a later call to window.open (e.g., when you want to call blur or focus):

window.open("", "theWindowName").focus();

But of course, if the window doesn’t already exist, that will open a new window. Sadly, you can’t know in advance (except in your application logic) whether a window with that name already exists.

Once you have the window object, you can call blur or focus.

Live Example | Source


Answer to your completely different, new question:

On Google Chrome, I can only focus() windows if an element has been clicked.

If your code opened the window, you should be able to. For example:

HTML:

<button id="btnOpen">Open</button>
<button id="btnFocus">Focus</button>

JavaScript:

jQuery(function($) {
  $("#btnOpen").click(function() {
    window.open(
      "about:blank",
      "theWindow",
      "width=500,height=500");
  });
  $("#btnFocus").click(function() {
    // Note that this happens a full second later, NOT
    // in direct response to a user event
    setTimeout(function() {
      window.open("", "theWindow").focus();
    }, 1000);
  });
});

Live Example | Source

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement