Search code examples
c#seleniumtimeoutwebdriver

Selenium Webdriver wait on element click?


I have been searching for a solution for this, but to no avail. I have a button I'm clicking, that is sometimes taking a long while to return data, and the driver is timing out and just killing the app I guess.

I am trying to use the WebDriverWait class to accomplish this, but the Click() method is not available in the way I'm using it.

WebDriverWait wait = new WebDriverWait(browser, new TimeSpan(0, 5, 0));

bool clicked = wait.Until<bool>((elem) =>
{
     elem.Click(); //Doesn't Work
     return true;
});

The ImplicitlyWait() method is only for waiting for elements to load, but this times out on Click(), so it can't even look for an element.

The SetScriptTimeout() method just works with executing javascript, which I'm not doing.

Does anyone know of a way to do this?


Solution

  • In addition to prestomanifesto's solution I can offer a less than ideal solution to that I implemented to solve this issue. It turns out it is throwing an exception - No Response etc... - so I just surrounded it in a try catch then waited for the popup to close, which seems to work fine.

    You can substitute whatever you want in your loop, just make sure to put a counter in so it won't loop forever.

    try
    {
        element.Click();
    }
    catch
    {
        cnt++;
        do
        {
          //wait for whatever
          cnt++;
          Thread.Sleep(1000);
          // Wait for 30 seconds for popup to close
        } while (!string.IsNullOrEmpty(browser.CurrentWindowHandle) && cnt < 30);
    }