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.
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.
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.
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.
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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With