To set the size of the browser window in Selenium Java, use the setSize()
method of the WebDriver.Window
interface in conjunction with the Dimension
class.
Step-by-step Guide
Import the Dimension class:
import org.openqa.selenium.Dimension;
Set the window size after initializing the WebDriver:
// Example: Set window size to 1024x768 pixels driver.manage().window().setSize(new Dimension(1024, 768));
This code resizes the current browser window to the specified width (1024) and height (768) in pixels.
Example Code
javaimport org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.Dimension; public class SetWindowSizeExample { public static void main(String[] args) { // Initialize the Chrome driver WebDriver driver = new ChromeDriver(); // Set browser window size to 1024x768 Dimension size = new Dimension(1024, 768); driver.manage().window().setSize(size); // Proceed with further actions or close the browser driver.quit(); } }
Key Points
- Syntax:
javadriver.manage().window().setSize(new Dimension(width, height));
Replacewidth
andheight
with the desired values in pixels. - This method sets the outer window size, not just the viewport.
- Setting window size is useful for responsive testing and simulating different device screen sizes.
You can adjust the width and height to fit your testing needs.