Data Browser - Viewing Site  Sector 23 Code Bank Logged in as:  Guest  




           


Selenium does not always Click on Anchor Links, Checkboxes, or other Elements
If you have an anchor link, the Click() method does not always cause the element to be clicked, even if it is clearly visible, in view, and clickable. Instead it intermittently does nothing (no fail, but no click).

In addition, when in debug mode with the InternetExplorerDriver, if you have breakpoints set, Selenium will only click Checkboxes every other time. (You have to call click twice for every checkbox).

I'm not sure what the exact issue is, but this extension method SafeClick seems to behave much better, by throwing everything we have at the click to get it to work, and using SendKeys for checkboxes/buttons. It is still not 100% reliable, but very close.

It relies on another extension method ScrollTo, which covers the case where the link is not on the visible screen area.

.NET C# usage:
myElement.ClickSafe();


/// <summary>
/// Ensure click works by scrolling to it and waiting for click ready state.
/// Simply calling 'Click' is not always reliable.
/// </summary>
/// <param name="el"></param>
/// <param name="driver"></param>
public static void ClickSafe(this IWebElement el, IWebDriver driver)
{
el.ScrollTo(driver);

Actions actions = new Actions(driver);
actions.MoveToElement(el).Build().Perform();

var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(ExpectedConditions.ElementToBeClickable(el));

Thread.Sleep(10);

if (el.TagName == "input" && el.GetAttribute("type") == "checkbox")
el.SendKeys(Keys.Space); // bug in Selenium: 'Click' is not 100% reliable when in debug mode with focus off the browser.
else if (el.TagName == "input" && el.GetAttribute("type") == "submit")
el.SendKeys(Keys.Enter); // bug in Selenium: 'Click' is not 100% reliable when in debug mode with focus off the browser.
else if (el.TagName == "input" && el.GetAttribute("type") == "button")
el.SendKeys(Keys.Enter); // bug in Selenium: 'Click' is not 100% reliable when in debug mode with focus off the browser.
else
el.Click();
}

/// <summary>
/// Scroll to this element so it is visible.
/// </summary>
/// <param name="el"></param>
/// <param name="driver"></param>
public static void ScrollTo(this IWebElement el, IWebDriver driver)
{
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].scrollIntoView(true);", el);
}

Created By: amos 3/4/2016 3:29:28 PM
Updated: 3/24/2016 2:54:46 PM