'How to extend Selenium to find a button with a specific text in C#, and making it work with implicit wait?

I'm trying to create an extension method which task is to find a button with a specific text. This is what I currently have:

public static IWebElement FindButtonByPartialText(this ISearchContext searchContext, string partialText)
{
    partialText = partialText.ToLowerInvariant();

    var elements = searchContext.FindElements(By.CssSelector("button, input[type='button']"));

    foreach (var e in elements)
    {
        if (e.TagName == "INPUT")
        {
            if (e.GetAttribute("value")?.ToLowerInvariant().Contains(partialText) == true)
                return e;
        }

        else if (e.Text.ToLowerInvariant().Contains(partialText))
            return e;
    }

    throw new Exception("foo");
}

(I have set the implicit wait option to 30 seconds)

So, if the page hasn't loaded properly yet, but there is at least one button on the page (with the incorrect text), this will fail miserably I expect, because it doesn't have the proper implicit wait behavior.

What is the correct way to create this extension method so that it waits the proper amount of time before throwing?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source