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:

require 'watir-webdriver'
b = Watir::Browser.new
b.goto 'www.google.com'
button = b.button(name: 'btnK')
button.driver #webdriver
button.browser #watir browser

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:

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);
}

This means it can be simply called like:

Driver.FindElement(By.Id("blah")).IsImageVisible();

instead of the cumbersome:

Driver.IsImageVisible(Driver.FindElement(By.Id("blah")));

Thanks Robert!

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.