The published Zechtitus code is amazing, I tried it in IE11 and Chrome version 39.0.2171.95 m, and it worked like a charm. Although I had to pass the real IWebDriver object instead of using WrappedDriver, because it does not work with Chrome. For your information only, I have Win 7 Ultimate x64 and using Selenium WebDriver 2.44. this is the code i took from zechtitus and changed it:
public static Rectangle GetAbsCoordinates(IWebDriver driver, IWebElement element) { var handle = GetIntPtrHandle(driver); var ae = AutomationElement.FromHandle(handle); AutomationElement doc = null; var caps = ((RemoteWebDriver)driver).Capabilities; var browserName = caps.BrowserName; switch (browserName) { case "safari": var conditions = (new AndCondition(new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Pane), new PropertyCondition(AutomationElement.ClassNameProperty, "SearchableWebView"))); doc = ae.FindFirst(TreeScope.Descendants, conditions); break; case "firefox": doc = ae.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Document)); break; case "chrome": doc = ae.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "Chrome Legacy Window")); if (doc == null) { doc = ae.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "Google Chrome")); if (doc == null) throw new Exception("unable to find element containing browser window"); doc = doc.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Document)); } break; case "internet explorer": doc = ae.FindFirst(TreeScope.Descendants, new AndCondition(new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Pane), new PropertyCondition(AutomationElement.ClassNameProperty, "TabWindowClass"))); break; } if (doc == null) throw new Exception("unable to find element containing browser window"); var iWinLeft = (int)doc.Current.BoundingRectangle.Left; var iWinTop = (int)doc.Current.BoundingRectangle.Top; var coords = ((ILocatable)element).Coordinates; var rect = new Rectangle(iWinLeft + coords.LocationInDom.X, iWinTop + coords.LocationInDom.Y, element.Size.Width, element.Size.Height); return rect; } public static IntPtr GetIntPtrHandle(this IWebDriver driver, int timeoutSeconds = 20) { var end = DateTime.Now.AddSeconds(timeoutSeconds); while (DateTime.Now < end) {
and I used it like this:
Rectangle recView = GetAbsCoordinates (MyWebDriverObj, myIWebElementObj);
the correct X, Y are then saved in recView.X and recView.Y As I said, it works for me for both IE11 and Chrome. Good luck.
source share