How do you switch focus to an alert in Selenium WebDriver using Java?
In response to your inquiry about switching focus to an alert in Selenium WebDriver using Java, I’d be happy to provide you with a comprehensive answer.
This is what worked for me using Explicit Wait from here WebDriver: Advanced Usage
public void checkAlert() { try { WebDriverWait wait = new WebDriverWait(driver, 2); wait.until(ExpectedConditions.alertIsPresent()); Alert alert = driver.switchTo().alert(); alert.accept(); } catch (Exception e) { //exception handling } }
Hi Kalyani
here is a comprehensive answer to guide you through the process and you could try:
try{ if(webDriver.switchTo().alert() != null){ Alert alert = webDriver.switchTo().alert(); alert.getText(); //etc. } }catch(Exception e){} If that doesn’t work, you could try looping through all the window handles and see if the alert exists. I’m not sure if the alert opens as a new window using selenium. for(String s: webDriver.getWindowHandles()){ //see if alert exists here. }
Hi Kalyani,
I appreciate the opportunity to provide you with the requested information/method. Below is the method you can follow: public boolean isAlertPresent() { try { driver.switchTo().alert(); return true; } // try catch (Exception e) { return false; } // catch } Now, you can check whether alert is present or not by using the method written above as below: if (isAlertPresent()) { driver.switchTo().alert(); driver.switchTo().alert().accept(); driver.switchTo().defaultContent(); }
I hope this addresses your inquiry. If you have any further questions or need clarification, please feel free to ask.