I am using Selenium WebDriver in conjunction with java.awt.Robot to better simulate user interaction with our web application. Yes, I know it’s probably unnecessary, but the customers I serve demand it.
Currently things are working pretty well, however I have a minor snag in that I can’t seem to find a good way to get the web elements’ on screen position. Things like the title bar, menu bar, navigation bar, etc all push the content down on the physical screen (which Robot gets its coordinates from), but has no impact on where Selenium reports the element is.
When I call: element.getLocation(); on a Selenium WebElement, it always gives me its location relative to the HTML content render pane, not the browser window itself.
A better illustration is: driver.findElement(By.tagName("body")).getLocation(); always returns 0,0, regardless of the window’s actual on-screen location.
Right now I am hacking it by adding a vertical and horizontal offset after maximizing the window, but these aren’t the same between different browsers (IE’s top decorations take up more room then Firefox’s, for example), and may be different for each user if they have bookmark tool bars, search bars, etc added in.
Yes, I know I could run in full screen mode, but I’d rather not, if at all possible.
Is there a way to use WebDriver to get the physical on-screen location of elements in a reliable manner?
I believe there’s no way to get the real on-screen location of the elements on the page.
I also think the fullscreen mode is your best bet.
That said, I wrote a
RobotCalibrationclass that can detect the real offsets of your current browser. It opens a specially crafted page and uses theRobotclass to click on it. The algorithm starts in the center of the browser and then uses bisecting to find the top left corner of the browser viewport.Tested on IE8 and FF18. Works for both maximized and windowed browsers. Known issue: If you have a top Bookmarks Toolbar enabled, it may click on some of the bookmarks and therefore redirect. It can be handled pretty easily, but I left it up to you if you needed that :).
The testing page:
The
RobotCalibrationclass. It’s a little bit long, so I suggest you to copypaste it into your favourite IDE and explore it there:Sample usage:
Feel free to ask any questions if something is unclear.