Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting WebDriver from IWebElement

Is it possible to get WebDriver from IWebElement?

I need the following extension:

public static bool HasFocus(this IWebElement e)
{
    var driver = ((????)e).WebDriver;

    var activeElement = driver.SwitchTo().ActiveElement();
    return Equals(activeElement, e);
}

But don't know is it possible to cast the IWebElement to some type to get WebDriver.

like image 589
msi Avatar asked Jul 10 '14 19:07

msi


People also ask

What is IWebElement selenium?

IWebElement is a selenium Web Element class which represents an HTML element (body, table, tr etc) on a page in your selenium automation code. With the IWebElement instance, you can interact with an element, retrieve it's attributes and properties.

What is IWebDriver and IWebElement?

The IWebDriver interface is the main interface to use for testing, which represents an idealized web browser. The methods in this class fall into three categories: Control of the browser itself. Selection of IWebElements. Debugging aids.

What is org Openqa selenium?

Describes a series of key/value pairs that encapsulate aspects of a browser. ContextAware. Some implementations of WebDriver, notably those that support native testing, need the ability to switch between the native and web-based contexts. Credentials.


2 Answers

The best way to get the WebDriver from an IWebElement is to distinguish whether the Object type is WebElementProxy or not, like this:

if (this.webElement.GetType().ToString() == 
    "OpenQA.Selenium.Support.PageObjects.WebElementProxy")
{
 this.WebDriver = ((IWrapsDriver)this.webElement
                  .GetType().GetProperty("WrappedElement")
                  .GetValue(this.webElement, null)).WrappedDriver;
}
else
{
  this.WebDriver = ((IWrapsDriver)this.webElement).WrappedDriver;
}
like image 135
janmbaco Avatar answered Oct 04 '22 22:10

janmbaco


I had recently the same problem but found out it's possible :)

This made my day: var driver = ((IWrapsDriver)e).WrappedDriver;

Note:If you use PageFactory to get IWebElement it's NOT possible then.

like image 22
Bart Wojtala Avatar answered Oct 04 '22 21:10

Bart Wojtala