Source:org.openqa.selenium.UnhandledAlertException: unexpected alert open
if (likely( everything_is_ok ))
{
/* Do something */
}
Best Selenium code snippet using org.openqa.selenium.NoAlertPresentException
org.openqa.selenium.NoAlertPresentException
This exception thrown due to accessing alert which is not present on screen.
Let's assumes when you are handling alert
specifically javascript alerts and you called Alert()
function before browser shows alert then you might encounter this exception.
Here are code snippets that can help you understand more how developers are using
Source:Browser.java
23import java.net.MalformedURLException;4import java.util.List;56import org.openqa.selenium.NoAlertPresentException;7import org.openqa.selenium.NoSuchElementException;8import org.openqa.selenium.NoSuchFrameException;9import org.openqa.selenium.NoSuchWindowException;10import org.openqa.selenium.WebElement;11import org.openqa.selenium.remote.RemoteWebDriver;1213import java.net.MalformedURLException;14import java.util.List;1516import org.openqa.selenium.NoAlertPresentException;17import org.openqa.selenium.NoSuchElementException;18import org.openqa.selenium.NoSuchFrameException;19import org.openqa.selenium.NoSuchWindowException;20import org.openqa.selenium.WebElement;2122public interface Browser {2324 /**25 * This method will launch the Chrome browser and maximise the browser and set26 * the wait for 30 seconds and load the url27 * 28 * @param url - This will load the specified url29 * @author Sarath - TestLeaf30 * @return31 * @throws MalformedURLException32 */33 public void startApp(String url);3435 /**36 * This method will launch the Any browser and maximise the browser and set the37 * wait for 30 seconds and load the url38 * 39 * @param browser - This will load the specified browser40 * @param url - This will load the specified url41 * @author Sarath - TestLeaf42 * @return43 * @throws MalformedURLException44 */45 public void startApp(String browser, String url);4647 /**48 * This method will locate the element using any given locator49 * 50 * @param locatorType - The locator by which the element to be found51 * @param locValue - The locator value by which the element to be found52 * @author Sarath - TestLeaf53 * @throws NoSuchElementException54 * @return The first matching element on the current context.55 */56 public WebElement locateElement(String locatorType, String value);5758 /**59 * This method will locate the element using id60 * 61 * @param locValue - The locator value by which the element to be found62 * @author Sarath - TestLeaf63 * @throws NoSuchElementException64 * @return The first matching element on the current context.65 */66 public WebElement locateElement(String value);6768 /**69 * This method will locates all matching element using any given locator70 * 71 * @param locatorType - The locator by which the element to be found72 * @param locValue - The locator value by which the element to be found73 * @author Sarath - TestLeaf74 * @return A list of all WebElements, or an empty list if nothing matches.75 */76 public List<WebElement> locateElements(String type, String value);7778 /**79 * This method will switch to the Alert80 * 81 * @author Sarath - TestLeaf82 * @return NoAlertPresentException83 */84 public void switchToAlert();8586 /**87 * This method will accept the alert opened88 * 89 * @author Sarath - TestLeaf90 * @throws NoAlertPresentException91 */92 public void acceptAlert();9394 /**95 * This method will dismiss the alert opened96 * 97 * @author Sarath - TestLeaf98 * @throws NoAlertPresentException99 */100 public void dismissAlert();101102 /**103 * This method will return the text of the alert104 * 105 * @author Sarath - TestLeaf106 * @throws NoAlertPresentException107 */108 public String getAlertText();109110 /**111 * This method will enter the value in the alert112 * 113 * @author Sarath - TestLeaf114 * @param data- the data to be entered in alert115 * @throws NoAlertPresentException116 */117 public void typeAlert(String data);118119 /**120 * This method will switch to the Window of interest121 * 122 * @param index The window index to be switched to. 0 -> first window123 * @author Sarath - TestLeaf124 * @throws NoSuchWindowException125 */126 public void switchToWindow(int index);127128 /**129 * This method will switch to the Window of interest using its title
...
Source:CommonMethods.java
1package com.utils;2import java.util.concurrent.TimeUnit;3import org.openqa.selenium.Alert;4import org.openqa.selenium.JavascriptExecutor;5import org.openqa.selenium.NoAlertPresentException;6import org.openqa.selenium.NoSuchFrameException;7import org.openqa.selenium.WebDriver;8import org.openqa.selenium.WebElement;9import org.openqa.selenium.chrome.ChromeDriver;10import org.openqa.selenium.firefox.FirefoxDriver;11public class CommonMethods {12 public static WebDriver driver;13 14 /**15 * Use this method in need of opening browser and target url16 * @param browser The desired browser17 * @param url The desired url18 */19 20 public static void setUp(String browser, String url) {21 22 if(browser.equalsIgnoreCase("chrome")) {23 System.setProperty("webdriver.chrome.driver", "drivers/chromedriver.exe");24 driver=new ChromeDriver();25 }else if(browser.equalsIgnoreCase("firefox")){26 System.setProperty("webdriver.gecko.driver", "drivers/geckodriver.exe");27 driver=new FirefoxDriver();28 }else {29 System.err.println("Browser not supported");30 }31 32 driver.manage().window().maximize();33 driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);34 driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);35 driver.get(url);36 }37 38 /**39 * This method will accept the alert 40 * @throws will throw a NoAlertPresentException if alert is not present41 */42 public static void acceptAlert() {43 try {44 Alert alert=driver.switchTo().alert();45 alert.accept();46 }catch(NoAlertPresentException e) {47 System.out.println("Alert is not present");48 }49 }50 51 52 /**53 * This method will dismiss the alert54 * @throws will throw a NoAlertPresentException if alert is not present 55 */56 public static void dismissAlert() {57 try {58 Alert alert=driver.switchTo().alert();59 alert.dismiss();60 }catch(NoAlertPresentException e) {61 System.out.println("Alert is not present");62 }63 }64 65 /**66 * This method will get a text from the alert67 * @return text of the alert68 * @throws will throw a NoAlertPresentException if alert is not present69 */70 71 public static String getTextAlert() {72 String text=null;73 try {74 Alert alert=driver.switchTo().alert();75 text=alert.getText();76 //return text;77 }catch(NoAlertPresentException e) {78 System.out.println("Alert is not present");79 }80 return text;81 }82 83 84 /**85 * This method will switch to the frame86 * @param nameOrId87 */88 public static void switchToFrame(String nameOrId) {89 try {90 driver.switchTo().frame(nameOrId);91 }catch(NoSuchFrameException e) {...
Source:BasePage.java
1package com.pactera.hris.base;23import org.openqa.selenium.Alert;4import org.openqa.selenium.NoAlertPresentException;5import org.openqa.selenium.WebDriver;6import org.openqa.selenium.interactions.Actions;7import org.openqa.selenium.support.ui.ExpectedConditions;8import org.openqa.selenium.support.ui.WebDriverWait;910import com.pactera.hris.info.Config;11import com.pactera.hris.util.Log;1213/**14 * 设置æ¥è§£æä¸åç±»ååçyamlæ件15 * BaePageåºç±»å¯ä»¥åæ¾ä¸äºéç¨Actionæä½æ¯å¦çªå£åæ¢ï¼é¼ æ Actionæä½ç16 * @author zhenhaiw17 *18 */1920public class BasePage extends Locator21{22 private Log logger = new Log(this.getClass().getName());23 24 public BasePage()25 {26 27 }28 29 public BasePage(WebDriver driver)30 {31 super(driver);32 this.setYaml(this.getClass().getSimpleName());33 this.loadYaml();34 }35 36 protected Actions getAction(){37 return new Actions(driver);38 }39 40 /**41 * æè·å¤ç页é¢å¯è½åºç°çAlert JS å¼¹çª42 * @param driver43 * @param option true - OK, false - cancel44 */45 46 public boolean isAlertPresent(WebDriver driver)47 {48 boolean flag = false;49 int waitTime = Config.WAITTIME;50 51 if(driver != null)52 {53 try 54 {55 Thread.sleep(Config.WAITTIME);56 new WebDriverWait(driver, waitTime).until(ExpectedConditions.alertIsPresent());57 flag = true;58 } catch (NoAlertPresentException e) 59 {60 logger.logInfo("There is no alert appear!");61 return flag;62 } catch (InterruptedException e) 63 {64 // TODO Auto-generated catch block65 e.printStackTrace();66 }67 }68 69 return flag;70 }71 72 public void dealPotentialAlert(WebDriver driver,boolean option) 73 {74 boolean flag = false;75 int waitTime = Config.WAITTIME;76 Alert alert = null;77 78 if(driver != null)79 {80 try 81 {82 Thread.sleep(Config.SLEEPTIME);83 alert = new WebDriverWait(driver, waitTime).until(ExpectedConditions.alertIsPresent());84 flag = true;85 86 if(flag)87 {88 alert = driver.switchTo().alert();89 if(option)90 {91 //注æalert.getText()æ¾å¨åé¢ï¼å¦åalert.accept()ä¹åæ¾ä¸å°alertå°±å¼å¸¸äº92 logger.logInfo("Accept the alert: " + alert.getText());93 alert.accept();94 }else95 {96 logger.logInfo("Dismiss the alert: " + alert.getText());97 alert.dismiss();98 }99 }100 } catch (NoAlertPresentException e) 101 {102 logger.logInfo("There is no alert appear!");103 } catch (InterruptedException e) 104 {105 // TODO Auto-generated catch block106 e.printStackTrace();107 }108 109 }else110 {111 return;112 }113 }114}
...
Source:Judge.java
...3import java.util.concurrent.TimeUnit;45import org.openqa.selenium.Alert;6import org.openqa.selenium.By;7import org.openqa.selenium.NoAlertPresentException;8import org.openqa.selenium.NoSuchElementException;9import org.openqa.selenium.WebDriver;10import org.openqa.selenium.WebDriverException;1112public class Judge {13 public boolean isElementExsit(WebDriver driver,By locator){14 try {15 driver.findElement(locator);16 return true;17 } catch (NoSuchElementException e) {18 return false;19 }20 }21 public boolean isByElementDisplayed(WebDriver driver,By by, int time) {22 boolean status = false;23 if (driver.findElement(by).isDisplayed() == false) {24 driver.manage().timeouts().implicitlyWait(time, TimeUnit.SECONDS);25 } else {26 status = true;27 }28 return status;29 }30 public boolean dealPotentialAlert(WebDriver driver,boolean option) { 31 boolean flag = false; 32 try { 33 Alert alert = driver.switchTo().alert(); 34 if (null == alert) 35 throw new NoAlertPresentException(); 36 try { 37 if (option) { 38 alert.accept(); 39// System.out.println("Accept the alert: " + alert.getText()); 40 } else { 41 alert.dismiss(); 42// System.out.println("Dismiss the alert: " + alert.getText()); 43 } 44 flag = true; 45 } catch (WebDriverException ex) { 46 if (ex.getMessage().startsWith("Could not find")) {47// System.out.println("There is no alert appear!"); 48 }49 else 50 throw ex; 51 } 52 } catch (NoAlertPresentException e) { 53// System.out.println("There is no alert appear!"); 54 } 55 return flag; 56 } 57}
...
Source:Alerts.java
1package com.base.selenium.features;2import org.openqa.selenium.NoAlertPresentException;3import org.openqa.selenium.TimeoutException;4import org.openqa.selenium.WebDriver;5import org.openqa.selenium.support.ui.ExpectedConditions;6import org.openqa.selenium.support.ui.WebDriverWait;78public class Alerts {9 10 WebDriver driver;11 12 public Alerts(WebDriver driver){13 this.driver=driver;14 }15 16 public boolean isAlertPresent(String alertTitleName){17 18 try{19 20 waitforAlert();21 return driver.switchTo().alert().getText().equals(alertTitleName);22 }catch(NoAlertPresentException e){23 return false;24 }25 }26 27 public void switchToDefaultContent(){28 29 driver.switchTo().defaultContent();30 }31 public void acceptAlert(){32 try{33 waitforAlert();34 driver.switchTo().alert().accept();35 }catch(NoAlertPresentException e){36 37 }38 }39 public void dismissAlert(){40 try{41 waitforAlert();42 driver.switchTo().alert().dismiss();43 }catch(NoAlertPresentException e){44 45 }46 }47 48 public void enterTextInAlert(String text){49 try{50 waitforAlert();51 driver.switchTo().alert().sendKeys(text);52 }catch(NoAlertPresentException e){53 54 }55 }5657 private boolean waitforAlert(){58 59 60 try{61 ExpectedConditions.alertIsPresent();62 //new WebDriverWait(driver,3).until(ExpectedConditions.alertIsPresent());63 64 return true;65 }catch(TimeoutException e){66 return false;
...
Source:SeleniumExample10.java
1import org.openqa.selenium.Alert;2import org.openqa.selenium.By;3import org.openqa.selenium.NoAlertPresentException;4import org.openqa.selenium.WebDriver;5import org.openqa.selenium.chrome.ChromeDriver;6public class SeleniumExample10 {7 public static void main(String[] args) throws NoAlertPresentException,InterruptedException { 8 System.setProperty("webdriver.chrome.driver", "C:\\Users\\ustjavasdetb413\\Downloads\\chromedriver.exe");9 WebDriver driver = new ChromeDriver();10 11 12 // Alert Message handling13 14 driver.get("http://demo.guru99.com/test/delete_customer.php"); 15 16 17 driver.findElement(By.name("cusid")).sendKeys("53920"); 18 driver.findElement(By.name("submit")).submit(); 19 20 // Switching to Alert 21 Alert alert = driver.switchTo().alert(); ...
Source:HelperBase.java
1package ru.stqa.ptf.addressbook.appmanager;2import org.openqa.selenium.By;3import org.openqa.selenium.NoAlertPresentException;4import org.openqa.selenium.WebElement;5import org.openqa.selenium.firefox.FirefoxDriver;6import org.openqa.selenium.support.ui.Select;7public class HelperBase {8 protected FirefoxDriver driver;9 public HelperBase(FirefoxDriver driver) {10 this.driver = driver;11 }12 protected void type(By locator, String text) {13 WebElement field = driver.findElement(locator);14 field.click();15 field.clear();16 field.sendKeys(text);17 }18 protected void select(By locator, String text) {19 WebElement selectElem = driver.findElement(locator);20 Select select = new Select(selectElem);21 select.selectByVisibleText(text);22 }23 protected void click(By locator) {24 WebElement buttonEnterInfo = driver.findElement(locator);25 buttonEnterInfo.click();26 }27 public boolean isAlertPresent () {28 try {29 driver.switchTo().alert();30 return true;31 } catch (NoAlertPresentException e) {32 return false;33 }34 }35}...
Source:AlertDemo.java
1package uiAutomation;2import org.openqa.selenium.Alert;3import org.openqa.selenium.By;4import org.openqa.selenium.NoAlertPresentException;5import org.openqa.selenium.WebDriver;6import org.openqa.selenium.chrome.ChromeDriver;7public class AlertDemo implements Common {8 public static void main(String[] args) throws NoAlertPresentException,InterruptedException {9 System.setProperty("webdriver.chrome.driver",driverPath);10 WebDriver driver = new ChromeDriver();11 // Alert Message handling12 driver.get("http://demo.guru99.com/test/delete_customer.php");13 driver.findElement(By.name("cusid")).sendKeys("53920");14 driver.findElement(By.name("submit")).submit();15 // Switching to Alert 16 Alert alert = driver.switchTo().alert();17 // Capturing alert message. 18 String alertMessage= driver.switchTo().alert().getText();19 // Displaying alert message 20 System.out.println(alertMessage);21 Thread.sleep(5000);22 // Accepting alert ...
NoAlertPresentException
Using AI Code Generation
1package org.openqa.selenium;2public class NoAlertPresentException extends WebDriverException {3 public NoAlertPresentException() {4 super();5 }6 public NoAlertPresentException(String message) {7 super(message);8 }9 public NoAlertPresentException(Throwable cause) {10 super(cause);11 }12 public NoAlertPresentException(String message, Throwable cause) {13 super(message, cause);14 }15}16package org.openqa.selenium;17public interface Alert {18 String getText();19 void sendKeys(String keysToSend);20 void accept();21 void dismiss();22}23package org.openqa.selenium;24public interface Alert {25 String getText();26 void sendKeys(String keysToSend);27 void accept();28 void dismiss();29}30package org.openqa.selenium;31import java.util.List;32public interface WebDriver extends SearchContext, JavascriptExecutor, TakesScreenshot {33 void get(String url);34 String getCurrentUrl();35 String getTitle();36 List<WebElement> findElements(By by);37 WebElement findElement(By by);38 String getPageSource();39 void close();40 void quit();41 Set<String> getWindowHandles();42 String getWindowHandle();43 TargetLocator switchTo();44 Navigation navigate();45 Options manage();46 public interface TargetLocator {47 WebDriver frame(int index);48 WebDriver frame(String nameOrId);49 WebDriver frame(WebElement frameElement);50 WebDriver parentFrame();51 WebDriver window(String nameOrHandle);52 WebElement activeElement();53 Alert alert();54 }55 public interface Navigation {56 void back();57 void forward();58 void to(String url);59 void to(URL url);60 void refresh();61 }62 public interface Options {63 Logs logs();64 interface Logs {65 Set<String> getAvailableLogTypes();66 LogEntries get(String logType);67 }68 Timeouts timeouts();69 interface Timeouts {70 Timeouts implicitlyWait(long time, TimeUnit unit);71 Timeouts setScriptTimeout(long time, TimeUnit unit);72 Timeouts pageLoadTimeout(long time, TimeUnit unit);73 }74 ImeHandler ime();75 interface ImeHandler {76 Set<String> getAvailableEngines();77 String getActiveEngine();78 boolean isActivated();79 void deactivate();80 void activateEngine(String engine);81 }82 Window window();83 interface Window {84 void setSize(Dimension targetSize);
NoAlertPresentException
Using AI Code Generation
1import org.openqa.selenium.NoAlertPresentException;2import org.openqa.selenium.WebDriver;3import org.openqa.selenium.firefox.FirefoxDriver;4public class NoAlertPresentExceptionExample {5 public static void main(String[] args) {6 WebDriver driver = new FirefoxDriver();7 try {8 driver.switchTo().alert().accept();9 } catch (NoAlertPresentException e) {10 System.out.println("No Alert Present");11 }12 driver.quit();13 }14}
NoAlertPresentException
Using AI Code Generation
1import org.openqa.selenium.NoAlertPresentException;2import org.openqa.selenium.WebDriver;3import org.openqa.selenium.firefox.FirefoxDriver;4public class NoAlertPresentExceptionDemo {5public static void main(String[] args) {6WebDriver driver = new FirefoxDriver();7try {8driver.switchTo().alert();9System.out.println("Alert is present");10} catch (NoAlertPresentException e) {11System.out.println("Alert is not present");12}13driver.close();14}15}
NoAlertPresentException
Using AI Code Generation
1import org.openqa.selenium.NoAlertPresentException;2import org.openqa.selenium.Alert;3import org.openqa.selenium.WebDriver;4import org.openqa.selenium.chrome.ChromeDriver;5import org.openqa.selenium.By;6import java.util.concurrent.TimeUnit;7public class NoAlertPresentExceptionDemo {8public static void main(String[] args) {9System.setProperty("webdriver.chrome.driver", "C:/Users/.../chromedriver.exe");10WebDriver driver = new ChromeDriver();11driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);12driver.findElement(By.name("cusid")).sendKeys("53920");13driver.findElement(By.name("submit")).submit();14try {15Alert alert = driver.switchTo().alert();16String alertMessage= driver.switchTo().alert().getText();17System.out.println(alertMessage);18alert.accept();19}20catch (NoAlertPresentException ex) {21ex.printStackTrace();22}23driver.close();24}25}
NoAlertPresentException
Using AI Code Generation
1import org.openqa.selenium.NoAlertPresentException;2public class NoAlertPresentExceptionDemo {3 public static void main(String[] args) {4 try {5 throw new NoAlertPresentException();6 } catch (NoAlertPresentException e) {7 e.printStackTrace();8 }9 }10}11 at NoAlertPresentExceptionDemo.main(NoAlertPresentExceptionDemo.java:14)
NoAlertPresentException
Using AI Code Generation
1package com.orgname.projectname;2import org.openqa.selenium.NoAlertPresentException;3import org.openqa.selenium.WebDriver;4import org.openqa.selenium.firefox.FirefoxDriver;5public class NoAlertPresentExceptionClass {6 public static void main(String[] args) {7 WebDriver driver = new FirefoxDriver();8 System.out.println("Successfully opened the website www.Store.Demoqa.com");9 try {10 Thread.sleep(5000);11 } catch (InterruptedException e) {12 e.printStackTrace();13 }14 String winHandleBefore = driver.getWindowHandle();15 driver.findElement(By.linkText("Product Category")).click();16 for(String winHandle : driver.getWindowHandles()){17 driver.switchTo().window(winHandle);18 }19 driver.findElement(By.linkText("iMacs")).click();20 driver.close();21 driver.switchTo().window(winHandleBefore);22 driver.findElement(By.linkText("iPhone 5s")).click();23 driver.quit();24 }25}
NoAlertPresentException
Using AI Code Generation
1package com.knoldus;2import org.openqa.selenium.*;3import org.openqa.selenium.chrome.*;4import org.openqa.selenium.support.ui.*;5import java.util.*;6public class NoAlertPresentExceptionDemo {7 public static void main(String[] args) {8 System.setProperty("webdriver.chrome.driver", "/home/knoldus/Downloads/chromedriver");9 WebDriver driver = new ChromeDriver();10 WebDriverWait wait = new WebDriverWait(driver, 2);11 try {12 Alert alert = wait.until(ExpectedConditions.alertIsPresent());13 System.out.println("alert is present");14 } catch (NoAlertPresentException e) {15 System.out.println("alert is not present");16 }17 }18}
1if (likely( everything_is_ok ))2{3 /* Do something */4}5
LambdaTest’s Selenium 4 tutorial is covering every aspects of Selenium 4 testing with examples and best practices. Here you will learn basics, such as how to upgrade from Selenium 3 to Selenium 4, to some advanced concepts, such as Relative locators and Selenium Grid 4 for Distributed testing. Also will learn new features of Selenium 4, such as capturing screenshots of specific elements, opening a new tab or window on the browser, and new protocol adoptions.
Upgrading From Selenium 3 To Selenium 4?: In this chapter, learn in detail how to update Selenium 3 to Selenium 4 for Java binding. Also, learn how to upgrade while using different build tools such as Maven or Gradle and get comprehensive guidance for upgrading Selenium.
What’s New In Selenium 4 & What’s Being Deprecated? : Get all information about new implementations in Selenium 4, such as W3S protocol adaption, Optimized Selenium Grid, and Enhanced Selenium IDE. Also, learn what is deprecated for Selenium 4, such as DesiredCapabilites and FindsBy methods, etc.
Selenium 4 With Python: Selenium supports all major languages, such as Python, C#, Ruby, and JavaScript. In this chapter, learn how to install Selenium 4 for Python and the features of Python in Selenium 4, such as Relative locators, Browser manipulation, and Chrom DevTool protocol.
Selenium 4 Is Now W3C Compliant: JSON Wireframe protocol is retiring from Selenium 4, and they are adopting W3C protocol to learn in detail about the advantages and impact of these changes.
How To Use Selenium 4 Relative Locator? : Selenium 4 came with new features such as Relative Locators that allow constructing locators with reference and easily located constructors nearby. Get to know its different use cases with examples.
Selenium Grid 4 Tutorial For Distributed Testing: Selenium Grid 4 allows you to perform tests over different browsers, OS, and device combinations. It also enables parallel execution browser testing, reads up on various features of Selenium Grid 4 and how to download it, and runs a test on Selenium Grid 4 with best practices.
Selenium Video Tutorials: Binge on video tutorials on Selenium by industry experts to get step-by-step direction from automating basic to complex test scenarios with Selenium.
LambdaTest also provides certification for Selenium testing to accelerate your career in Selenium automation testing.
Get 100 minutes of automation test minutes FREE!!