How to resize the browser window, zoom in or zoom out the page content in Selenium?

Sometimes we need to resize the browser window in our Selenium tests. There could be various scenarios why we would want to do that.

While debugging a failure on remote execution vs local execution there could be a case that the tests are running with a specific browser size when executed via CI/CD mechanism on a remote VM or container. So to debug the issue we need to set the same browser size in our local execution as well.

Or we may want to test responsiveness of the UI on different browser sizes.

Let us explore different ways by which we can achieve it:

Set window size in Options before launching the browser

ChromeOptions options = new ChromeOptions();
options.addArguments("window-size=800, 400");
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
WebDriver driver = new ChromeDriver(capabilities);
driver.get("https://www.google.com");

You would need to import the following packages:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;

Set a custom browser size in-between the test code

At any point of the test after launching the browser, you can resize the browser window:

driver.get("https://www.google.com");
//Do something
//do something more
//blah blah blah
Dimension dimension = new Dimension(800, 400);
//Resize current window to the set dimension
driver.manage().window().setSize(dimension);

You would need to import the following:

import org.openqa.selenium.Dimension;

Run tests in full screen mode

You can maximize your browser window at any time after launching the browser i.e after calling driver.get()

driver.manage().window().maximize();

Zoom in or zoom out the page

You can inject the following JavaScript code in the browser to zoom in/out the page. Please feel free to refer This Tutorial if you want to read about executing JavaScript in Selenium.

String scaleX = "1";
String scaleY = "1";
String js = document.body.style.transform='scale(scaleX, scaleY)';

JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript(js);
  • If you want to zoom in, you need to specify a value greater than 1. For instance a value of 1.5 would meaning zooming in for 150%.
  • For zooming out it the value should be between 0.0 to 1.
  • The value 1 refers to the original page size i.e 100% zoom.

So you can zoom in/out, test your thing and can get back to the the original page size by running the following code again:

js.executeScript(document.body.style.transform='scale(1, 1)');

2 thoughts on “How to resize the browser window, zoom in or zoom out the page content in Selenium?”

Leave a Reply