Getting the WebDriver driver from a WebDriver element

In watir-webdriver it is really easy to access both the webdriver driver and the watir browser objects from an element:

[sourcecode language=”ruby” light=”true”]
require ‘watir-webdriver’
b = Watir::Browser.new
b.goto ‘www.google.com’
button = b.button(name: ‘btnK’)
button.driver #webdriver
button.browser #watir browser
[/sourcecode]

I never knew how to do this in C# until someone named Robert left a comment yesterday on an old blog post with instructions on how to do so.

You can get the webdriver by using.
var driver = ((IWrapsDriver)webElement).WrappedDriver;

Neat. This means the C# check image present extension method I wrote about previously can be implemented directly from the element itself:

[sourcecode language=”csharp” light=”true”]
public static bool IsImageVisible(this IWebElement image)
{
var driver = ((IWrapsDriver)image).WrappedDriver;
var script = TestConfig.DriverType == "ie"
? "return arguments[0].complete"
: "return (typeof arguments[0].naturalWidth!=\"undefined\"" +
" && arguments[0].naturalWidth>0)";
return (bool)((IJavaScriptExecutor)driver).ExecuteScript(script, image);
}
[/sourcecode]

This means it can be simply called like:

[sourcecode language=”csharp” light=”true”]
Driver.FindElement(By.Id("blah")).IsImageVisible();
[/sourcecode]

instead of the cumbersome:

[sourcecode language=”csharp” light=”true”]
Driver.IsImageVisible(Driver.FindElement(By.Id("blah")));
[/sourcecode]

Thanks Robert!

Author: Alister Scott

Alister is a Software Quality Engineer for Automattic.

2 thoughts on “Getting the WebDriver driver from a WebDriver element”

  1. Curious to wonder, the blog comment tip is for C#. Is there a wrapped driver equivalent in Java (and how about Python, Ruby, and the JSONWireProtocol)?

Comments are closed.