Wednesday 5 August 2015

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));

1 comment:

  1. Sometimes we have code that craps out when one is resizing the browser window. As such, this method of resizing the window will not be useful to catch the problem. Sure, it will resize the window alright, but I'd like to see Selenium be able to grab the window edge with a mouse click and move it to a new size, thus causing the browser to keep firing events to update its size, and therefore, exercizing the problematic code...

    ReplyDelete