I am trying to extend the interface IWebElement
in C# to add a new method to protect against StaleElementReferenceException
.
The method I want to add is a simple retryingClick
that will try to click the WebElement up to three times before giving up:
public static void retryingClick(this IWebElement element)
{
int attempts = 0;
while (attempts <= 2)
{
try
{
element.Click();
}
catch (StaleElementReferenceException)
{
attempts++;
}
}
}
The reason to add the method is that our webpage makes extensive use of jQuery and a lot of elements are dynamically created/destroyed, so adding protection for each WebElement
becomes a huge ordeal.
So the question becomes: how should I implement this method so the interface IWebElement
can always make use of it?
Thank you, Regards.
For anyone that reaches the has the same question, here is how I fixed it:
Create a new static class
ExtensionMethods:
public static class ExtensionMethods
{
public static bool RetryingClick(this IWebElement element)
{
Stopwatch crono = Stopwatch.StartNew();
while (crono.Elapsed < TimeSpan.FromSeconds(60))
{
try
{
element.Click();
return true;
}
catch (ElementNotVisibleException)
{
Logger.LogMessage("El elemento no es visible. Reintentando...");
}
catch (StaleElementReferenceException)
{
Logger.LogMessage("El elemento ha desaparecido del DOM. Finalizando ejecución");
}
Thread.Sleep(250);
}
throw new WebDriverTimeoutException("El elemento no ha sido clicado en el tiempo límite. Finalizando ejecución");
}
}
This should be enough for the method RetryingClick
to appear as a method for the IWebElement type
If you have any doubts, check the Microsoft C# Programing guide for Extension Methods
Hope this helps