Search code examples
javaseleniumtimeout

Selenium how prompt message box when page is not responding or timeout on finding the element?


I am using Internet Explorer Version 11.0.85, and currently this IE having issues of page not responding or timeout while running a selenium randomly. how can i detect when page is not responding or selenium is having timeout while running and prompt a message box using JOptionpane?

Things that i want to achieve

  1. If Page Not Responding it will prompt message box.
  2. If Selenium having timeout because it cannot find the element it need to click it will prompt a message box.

i have test many possibilities like Get attribute, try catch, Timeouts().SetScriptTimeoutSince. but none of me make me achieve result that i want, is either i write it wrongly or not is hard to tell because i need to keep run until it stuck to see the result. anyone that have try this and have code that working to handle this 2 situation is really appreciate your help thanks!

Update

I have try this code it seem working properly and expected following pburgr example, but just i cannot put more than 1 exception in code any idea why it cannot be?

    try {

    // TimeSheet Button
    waitForElementLocatedBy(driver,timesheet);
    driver.findElement(timesheet).sendKeys(Keys.ENTER);

    } catch (TimeoutException e) {
    // TODO: handle exception
    messageBox("Error Occur");
    }



    public static void messageBox(String message) {
    final JDialog dialog = new JDialog();
    dialog.setAlwaysOnTop(true);    
    JOptionPane.showMessageDialog(dialog, message,"Information", JOptionPane.INFORMATION_MESSAGE); 
    }

    public static void waitForElementLocatedBy(WebDriver driver, By locator) {
        new WebDriverWait(driver, 10).until(ExpectedConditions.presenceOfElementLocated(locator));
   }

Solution

  • Try - catch with waiting on ExpectedConditions should make the job.

    try {wait_sec(driver, 5).until(ExpectedConditions.elementToBeClickable(By.id("foo")));} catch (TimeoutException | NoSuchElementException e) {msg("Problem with loading the page occured.");}
    

    or

    try {wait_sec(driver, 5).until(ExpectedConditions.numberOfElementsToBeMoreThan(By.id("foo"), 1));} catch (TimeoutException | NoSuchElementException e) {msg("Problem with loading the page occured.");}
    

    or some other

    // modified wait method
    public WebDriverWait wait_sec(WebDriver driver, int sec) {
        return new WebDriverWait(driver, sec);
    }
    
    
    // display msgbox
    public void msg(String string) {
        final JDialog dialog = new JDialog();
        dialog.setAlwaysOnTop(true);    
        JOptionPane.showMessageDialog(dialog, string);
    }