Is there a way to return the new absolute co-ordinates of an off-screen element after it has scrolled into view?
I've tried refreshing the element by extracting it's xPath
String xPath = generateXpath(this.currentElement, "");
this.currentElement = driver.findElement(By.xpath(xPath));
Here is my current code:
//Output initial X, Y coordinates
System.out.println ("X: "+ String.valueOf(this.currentElement.getAttribute("offsetTop")));
System.out.println ("Y: "+ String.valueOf(this.currentElement.getAttribute("offsetLeft")));
//X: 495
//Y: 3109
//Scroll object into view at the bottom of the page
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(false);", this.currentElement);
this.currentElement.sendKeys(Keys.ARROW_DOWN);
this.currentElement.sendKeys(Keys.ARROW_DOWN);
//Output new absolute X, Y coordinates
System.out.println ("X: "+ String.valueOf(this.currentElement.getAttribute("offsetTop")));
System.out.println ("Y: "+ String.valueOf(this.currentElement.getAttribute("offsetLeft")));
//Same as original coordinates
//X: 495
//Y: 3109
Expected results is the new absolute screen position
X: 495 Y: 997
First move the browser to the physical 0, 0 location on the desktop. Note: in some cases Selenium will place the browser a few pixels to the right of 0, 0. Thus the .setPosition may need to be offset for accuracy.
driver.manage().window().setPosition(new Point(-5,0)); //offset
Next use JavaScript to return the getBoundingClientRect().left and getBoundingClientRect().top values to return the x and y co-ordinates. Again offsets will need to be used for accuracy.
public static int getAbsY(WebDriver driver, WebElement element) {
double y = (double) ((JavascriptExecutor) driver).executeScript(
"return arguments[0].getBoundingClientRect().top", element);
return (int) y + 25; //Offset
}
public static int getAbsX(WebDriver driver, WebElement element) {
double x = (double) ((JavascriptExecutor) driver).executeScript(
"return arguments[0].getBoundingClientRect().left", element);
return (int) x + 12; //Offset
}
Finally use the Robot class to move the mouse to the element location to ensure location accuracy.
public static void moveMouseTo(WebDriver driver, WebElement element){
int x = getAbsX(driver, element);
int y = getAbsY(driver, element);
Robot robot = null;
try {
robot = new Robot();
} catch (AWTException e) {
}
robot.mouseMove(x, y);
}
moveMouseTo(element);
As for why one would want to do this: Professional level SDETs often will create element descriptions on the fly in their test automation frameworks. This will visually ensure the correct element has been located.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.