To set the position of the browser window in Selenium Java, use the setPosition()
method from the WebDriver.Window
interface. This method moves the browser window to the specified (X, Y) screen coordinates, where (0, 0) is the top-left corner of your screen.
Syntax
import org.openqa.selenium.Point;
// Move window to X=100, Y=200
driver.manage().window().setPosition(new Point(100, 200));
- The X coordinate sets the horizontal distance from the left edge of the screen.
- The Y coordinate sets the vertical distance from the top edge of the screen.
Complete Code
import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.Point; public class SetWindowPosition { public static void main(String[] args) { WebDriver driver = new ChromeDriver(); driver.get("https://www.google.com"); // Set window position to X=100, Y=200 driver.manage().window().setPosition(new Point(100, 200)); // Optional: Fetch and print actual window position Point position = driver.manage().window().getPosition(); System.out.println("Window position: X=" + position.getX() + " Y=" + position.getY()); driver.quit(); } }
Key Points
- Use positive coordinates to keep the window visible on-screen. Negative values will shift portions of the window off-screen.
- This technique is useful when running multiple tests in parallel and wanting to organize browser windows on the screen.
- You can retrieve the current window position using:
Point currentPosition = driver.manage().window().getPosition();
int x = currentPosition.getX();
int y = currentPosition.getY();
This approach provides precise control over the on-screen position of your Selenium-controlled browser window.