Wednesday, February 19, 2014

Maximize and Resize browser window in Selenium Webdriver

Maximize browser window:
You can maximize your current browser window by simply calling the maximize() method of WebDriver as below:
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
Sometimes the above doesn't work in some versions of browsers like chrome. So you can use below code alternatively:
Point targetPosition = new Point(0, 0);
driver.manage().window().setPosition(targetPosition);

String w = "return screen.availWidth";
String h = "return screen.availHeight";
JavascriptExecutor javascriptExecutor = (JavascriptExecutor) driver;
int width = ((Long) javascriptExecutor.executeScript(w)).intValue();
int height = ((Long) javascriptExecutor.executeScript(h))
  .intValue();
Dimension targetSize = new Dimension(width, height);

driver.manage().window().setSize(targetSize);

Resize browser window:
Sometimes in the test we need to resize the browser window to a certain window size. In such cases we can use the below to do:
driver.manage().window().setSize(new Dimension(320, 480));