Skip to content

Instantly share code, notes, and snippets.

@lsloan
Created August 16, 2016 17:19
Show Gist options
  • Save lsloan/d55e00f14bb1ce9fefef231005ba9980 to your computer and use it in GitHub Desktop.
Save lsloan/d55e00f14bb1ce9fefef231005ba9980 to your computer and use it in GitHub Desktop.
JavaScript: Focus on a newly opened window or tab.

Many web browsers will let JavaScript code open a new window (or tab) using the Window class. However, whether the new view is shown as a window or tab cannot be specified by JS. It is entirely under the control of the browser, which may let the user specify how new windows should appear. Rightfully so, the user should be in control of their environment.

However, not all browsers will focus on the new view after it opens. For example, if the user specifies that Google Chrome should open new windows as tabs, those new tabs will be loaded in the background. The user will not see the contents until they explicitly select that tab for viewing.

Using the Window.focus() method, though, lets the JS code force the new view to come to the foreground. This is an example of a function that can be used to open a new view and force it into focus if necessary:

function openInNewWindowAndFocus(url) {
  var newWindow = window.open(url, '_blank');
  newWindow.focus();
}

A one-line version that does the same:

window.open('http://www.example.org/', '_blank').focus()

The benefit of the one-line version is that it's short and may be used in some places where it's not possible to define a function. A benefit of the multiline function version is that the newWindow object may be used to perform other operations on the newly-opened view.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment