user1402913
user1402913

Reputation: 181

Make sure that browser opened by webdriver is always in focus

If the browser window is not in focus, all webdriver identifications on the current page fail.

How can the browser be brought into focus, using webdriver?

Upvotes: 18

Views: 47105

Answers (7)

MarmaladeToast2
MarmaladeToast2

Reputation: 1

(Python solution) This seems to perform consistently for Chrome and snatches focus and the foreground window layer without resizing the window.

driver.minimize_window()
driver.switch_to.window(driver.current_window_handle)

Upvotes: 0

dokcn
dokcn

Reputation: 107

This works for me (in python):

driver.minimize_window()
driver.maximize_window()

Upvotes: 0

omar chenge
omar chenge

Reputation: 1

Setting the focus at the "driver options" should work:

InternetExplorerOptions options = new InternetExplorerOptions();
options.setCapability("requireWindowFocus", true);

Upvotes: 0

davnicwil
davnicwil

Reputation: 30957

executeScript("window.focus();") didn't work for me in the latest Chrome (v47 at the time of this post)

However I found a hack in another question which does work in this version of Chrome.

Here are the generic steps, since the question doesn't specify the Selenium API language:

  1. Show alert by executing script in browser
  2. Accept the alert

Implementation in webdriverjs, which I'm using

const chrome = setupChromeWebdriver(); // get your webdriver here

chrome.executeScript('alert("Focus window")'))
  .then(() => chrome.switchTo().alert().accept());

Upvotes: 9

Testilla
Testilla

Reputation: 692

This works for me. After the code that opens the browser, issue this snippet:

String window = driver.getWindowHandle();
((JavascriptExecutor) driver).executeScript("alert('Test')");
driver.switchTo().alert().accept();
driver.switchTo().window(window);

Upvotes: 3

JWP
JWP

Reputation: 6963

Selenium 3.0 takes this:

((IJavaScriptExecutor)po.WebDriver).ExecuteScript("window.focus();");

Upvotes: 1

Ashwin Prabhu
Ashwin Prabhu

Reputation: 7624

((JavascriptExecutor) webDriver).executeScript("window.focus();");

should do the trick!

Upvotes: 6

Related Questions