Getting Browser Details in WebDriver

While not a major requirement getting the browser name and version could come in useful in test reports. Use the following code snippet to get the browser name and version:

browser

ICapabilities cap = ((RemoteWebDriver)driver).Capabilities;
string strBrowserName = cap.BrowserName;
string strBrowserVersion = cap.Version;
            
Console.WriteLine("Testing on Browser {0} v{1}", strBrowserName, strBrowserVersion);
Advertisements

Checking a checkbox with WebDriver

For something as simple as checking a checkbox you would think that all the different browser drivers would implement this in the same way. But sadly this is not the case. Firefox expects that you click on a checkbox to check or uncheck it whereas both the IEDriver and ChromeDriver expect you to type a space to do the same. This is all well and good for running a simple once off test, but we cant be expected to change code and re-build every time we want to test in a different browser.

Thankfully there is a solution at hand. Once we know which browser is currently running the test, we can decide which method to use. I have provided a C# and a Java code snippet below:

C#

IWebElement checkbox = driver.FindElement(By.Id("ElementID"));

if (((RemoteWebDriver)driver).Capabilities.BrowserName == "firefox")
{
    // Firefox
    checkbox.Click();
}
else
{
    // Chrome and IE
    checkbox.SendKeys(Keys.Space);
}

Java

WebElement checkbox = driver.findElement(By.id("idOfTheElement");

if (driver.Capabilities.BrowserName.Equals("firefox"))
{
    checkbox.Click();
}
else
{
    checkbox.SendKeys(Keys.Space);
}

If you come across any other discrepancies between the different driver implementations let us know in the comments.