get Absolute Position of a WebElement

2,792 views
Skip to first unread message

Graham

unread,
Apr 25, 2012, 10:53:33 AM4/25/12
to webd...@googlegroups.com
Hi,

I'm trying to find the absolute position of a webelement which is located in an iFrame. 

I've tried using both getLocation() and getCoordinates() and while getCoordinates seems to be a bit better it's still not 100% correct. 

Has anyone come up with a way to find the absolute position relation to the browser window?

thanks,
graham

darrell

unread,
Apr 26, 2012, 11:23:01 AM4/26/12
to webdriver
A generic answer might be a little tricky. Generally speaking, if you
are trying to find an element you have to do the following:

- find the iframe
- switch to the iframe
- find the element

If the element is in an iframe, inside an iframe, inside an iframe,
etc. this is where a generic solution gets tricky. If you are looking
for a solution to a specific application then the algorithm is:

- find the iframe
- get the iframe Location
- get the X value
- get the Y value
- switch to the iframe
- find the element
- get the element Location
- add the X value to the above X value
- add the Y value to the above Y value

The indented lines are additions to the original algorithm. In actual
code:

public Point getAbsoluteLocation(By iframeLocator, By elementLocator)
{
Point p;
WebElement iframe = driver.findElement(iframeLocator);
Point iframeLoc = iframe.getLocation();
int x = iframeLoc.getX();
int y = iframeLoc.getY();
driver.switchTo().frame(iframe);
WebElement element = driver.findElement(elementLocator);
Point elementLoc = element.getLocation();
x += elementLoc.getX();
y += elementLoc.getY();
p = new Point(x, y);
return p;

Graham

unread,
Apr 26, 2012, 12:16:36 PM4/26/12
to webd...@googlegroups.com
Thanks Darrell, I had come to a similiar conclusion myself.

I was trying to do something similar on android and noticed that getLocation() returns the position based on the screen, not the top of the document. Basically I'm taking a screenshot and put a border around a given element so this messed it up. I was able to get the scrolling offset like so:

JavascriptExecutor je = (JavascriptExecutor) webDriver();
Object pageYOffset = je.executeScript("return window.pageYOffset;");
scrollHeight = ((Long) pageYOffset).intValue(); 
Reply all
Reply to author
Forward
0 new messages