How to use UnhandledAlertException class of org.openqa.selenium package

Best Selenium code snippet using org.openqa.selenium.UnhandledAlertException

Source:AlertsTest.java Github

copy

Full Screen

...23import org.junit.Test;24import org.openqa.selenium.By;25import org.openqa.selenium.JavascriptExecutor;26import org.openqa.selenium.NoAlertPresentException;27import org.openqa.selenium.UnhandledAlertException;28import org.openqa.selenium.WebElement;29import org.openqa.selenium.testing.JUnit4TestBase;30import org.openqa.selenium.testing.NeedsLocalEnvironment;31import java.util.concurrent.TimeUnit;32@NeedsLocalEnvironment(reason = "Requires local browser launching environment")33public class AlertsTest extends JUnit4TestBase {34 @AfterClass35 public static void quitDriver() {36 JUnit4TestBase.removeDriver();37 }38 @Before39 public void setUp() throws Exception {40 driver.get(pages.alertsPage);41 }42 @Test43 public void testShouldBeAbleToOverrideTheWindowAlertMethod() {44 ((JavascriptExecutor) driver).executeScript(45 "window.alert = function(msg) { document.getElementById('text').innerHTML = msg; }");46 driver.findElement(By.id("alert")).click();47 }48 @Test49 public void testHandlesWhenNoAlertsArePresent() {50 try {51 driver.switchTo().alert();52 } catch (NoAlertPresentException expected) {53 }54 }55 @Test56 public void testCatchesAlertsOpenedWithinAnIFrame() {57 driver.switchTo().frame("iframeWithAlert");58 try {59 driver.findElement(By.id("alertInFrame")).click();60 } catch (UnhandledAlertException expected) {61 }62 // If we can perform any action, we're good to go63 assertEquals("Testing Alerts", driver.getTitle());64 }65 @Test66 public void throwsIfScriptTriggersAlert() {67 driver.get(pages.simpleTestPage);68 driver.manage().timeouts().setScriptTimeout(5000, TimeUnit.MILLISECONDS);69 try {70 ((JavascriptExecutor)driver).executeAsyncScript("setTimeout(arguments[0], 200) ; setTimeout(function() { window.alert('Look! An alert!'); }, 50);");71 fail("Expected UnhandledAlertException");72 } catch (UnhandledAlertException expected) {73 // Expected exception74 }75 // Shouldn't throw76 driver.getTitle();77 }78 @Test79 public void throwsIfAlertHappensDuringScript() {80 driver.get(pages.slowLoadingAlertPage);81 driver.manage().timeouts().setScriptTimeout(5000, TimeUnit.MILLISECONDS);82 try {83 ((JavascriptExecutor)driver).executeAsyncScript("setTimeout(arguments[0], 1000);");84 fail("Expected UnhandledAlertException");85 } catch (UnhandledAlertException expected) {86 //Expected exception87 }88 // Shouldn't throw89 driver.getTitle();90 }91 @Test92 public void throwsIfScriptTriggersAlertWhichTimesOut() {93 driver.get(pages.simpleTestPage);94 driver.manage().timeouts().setScriptTimeout(5000, TimeUnit.MILLISECONDS);95 try {96 ((JavascriptExecutor)driver).executeAsyncScript("setTimeout(function() { window.alert('Look! An alert!'); }, 50);");97 fail("Expected UnhandledAlertException");98 } catch (UnhandledAlertException expected) {99 // Expected exception100 }101 // Shouldn't throw102 driver.getTitle();103 }104 @Test105 public void throwsIfAlertHappensDuringScriptWhichTimesOut() {106 driver.get(pages.slowLoadingAlertPage);107 driver.manage().timeouts().setScriptTimeout(5000, TimeUnit.MILLISECONDS);108 try {109 ((JavascriptExecutor)driver).executeAsyncScript("");110 fail("Expected UnhandledAlertException");111 } catch (UnhandledAlertException expected) {112 //Expected exception113 }114 // Shouldn't throw115 driver.getTitle();116 }117 @Test118 public void testIncludesAlertInUnhandledAlertException() {119 try {120 driver.findElement(By.id("alert")).click();121 fail("Expected UnhandledAlertException");122 } catch (UnhandledAlertException e) {123 assertAlertText("cheese", e);124 }125 }126 @Test127 public void shouldCatchAlertsOpenedBetweenCommandsAndReportThemOnTheNextCommand()128 throws InterruptedException {129 driver.get(pages.alertsPage);130 ((JavascriptExecutor)driver).executeScript(131 "setTimeout(function() { alert('hi'); }, 250);");132 Thread.sleep(1000);133 try {134 driver.getTitle();135 } catch (UnhandledAlertException expected) {136 assertAlertText("hi", expected);137 }138 // Shouldn't throw139 driver.getTitle();140 }141 @Test142 public void onBeforeUnloadWithNoReturnValueShouldNotTriggerUnexpectedAlertErrors() {143 driver.get(pages.alertsPage);144 JavascriptExecutor executor = (JavascriptExecutor) driver;145 assertEquals(0L,146 executor.executeScript("localStorage.clear(); return localStorage.length"));147 executor.executeScript(148 "window.onbeforeunload = function() {\n" +149 " localStorage.setItem('foo', 'bar');\n" +150 "};");151 driver.navigate().refresh();152 assertEquals("onbeforeunload did not run!",153 "bar", executor.executeScript("return localStorage.getItem('foo');"));154 }155 @Test156 public void157 onBeforeUnloadWithNoReturnValueShouldNotTriggerUnexpectedAlertErrors_firedBetweenCommands()158 throws InterruptedException {159 driver.get(pages.alertsPage);160 JavascriptExecutor executor = (JavascriptExecutor) driver;161 assertEquals(0L,162 executor.executeScript("localStorage.clear(); return localStorage.length"));163 executor.executeScript(164 Joiner.on("\n").join(165 "window.onbeforeunload = function() {",166 " localStorage.setItem('foo', 'bar');",167 "};",168 "var newUrl = arguments[0];",169 "window.setTimeout(function() {",170 " window.location.href = newUrl;",171 "}, 500);"),172 pages.iframePage);173 // Yes, we need to use a dirty sleep here. We want to ensure the page174 // reloads and triggers onbeforeunload without any WebDriver commands.175 Thread.sleep(1500);176 assertEquals(pages.iframePage, driver.getCurrentUrl());177 assertEquals("onbeforeunload did not run!",178 "bar", executor.executeScript("return localStorage.getItem('foo');"));179 }180 @Test181 public void onBeforeUnloadWithNullReturnDoesNotTriggerAlertError() {182 driver.get(pages.alertsPage);183 JavascriptExecutor executor = (JavascriptExecutor) driver;184 assertEquals(0L,185 executor.executeScript("localStorage.clear(); return localStorage.length"));186 executor.executeScript(187 "window.onbeforeunload = function() {\n" +188 " localStorage.setItem('foo', 'bar');\n" +189 " return null;\n" +190 "};");191 driver.navigate().refresh();192 assertEquals("onbeforeunload did not run!",193 "bar", executor.executeScript("return localStorage.getItem('foo');"));194 }195 @Test196 public void onBeforeUnloadFromPageLoadShouldTriggerUnexpectedAlertErrors() {197 driver.get(pages.alertsPage);198 setSimpleOnBeforeUnload("one two three");199 try {200 driver.get(pages.alertsPage);201 fail("Expected UnhandledAlertException");202 } catch (UnhandledAlertException e) {203 assertAlertText("one two three", e);204 }205 }206 @Test207 public void onBeforeUnloadFromPageRefreshShouldTriggerUnexpectedAlertErrors() {208 driver.get(pages.alertsPage);209 setSimpleOnBeforeUnload("one two three");210 try {211 driver.navigate().refresh();212 fail("Expected UnhandledAlertException");213 } catch (UnhandledAlertException e) {214 assertAlertText("one two three", e);215 }216 }217 @Test218 public void219 onBeforeUnloadWithReturnValuesShouldTriggerUnexpectedAlertErrors_uiAction() {220 driver.get(pages.alertsPage);221 JavascriptExecutor executor = (JavascriptExecutor) driver;222 WebElement body = (WebElement) executor.executeScript(223 "var newPage = arguments[0];" +224 "window.onbeforeunload = function() { return 'one two three'; };" +225 "document.body.onclick = function() { window.location.href = newPage; };" +226 "return document.body;",227 pages.simpleTestPage);228 body.click();229 try {230 driver.getTitle();231 fail("Expected UnhandledAlertException");232 } catch (UnhandledAlertException e) {233 assertAlertText("one two three", e);234 }235 }236 @Test237 public void238 onBeforeUnloadWithReturnValuesShouldTriggerUnexpectedAlertErrors_asyncScript() {239 driver.get(pages.alertsPage);240 setSimpleOnBeforeUnload("one two three");241 try {242 ((JavascriptExecutor) driver).executeAsyncScript(243 "window.location = arguments[0]", pages.alertsPage);244 fail("Expected UnhandledAlertException");245 } catch (UnhandledAlertException e) {246 assertAlertText("one two three", e);247 }248 }249 private static void assertAlertText(String expectedText, UnhandledAlertException e) {250 assertEquals(expectedText, e.getAlertText());251 }252 private void setSimpleOnBeforeUnload(Object returnValue) {253 ((JavascriptExecutor) driver).executeScript(254 "var retVal = arguments[0]; window.onbeforeunload = function() { return retVal; }",255 returnValue);256 }257}...

Full Screen

Full Screen

Source:TestDomXSS.java Github

copy

Full Screen

...3import java.util.List;4import org.apache.log4j.Logger;5import org.openqa.selenium.By;6import org.openqa.selenium.ElementNotVisibleException;7import org.openqa.selenium.UnhandledAlertException;8import org.openqa.selenium.WebDriver;9import org.openqa.selenium.WebDriverException;10import org.openqa.selenium.WebElement;11import org.openqa.selenium.chrome.ChromeDriver;12import org.openqa.selenium.firefox.FirefoxDriver;13import org.openqa.selenium.ie.InternetExplorerDriver;14import org.parosproxy.paros.core.scanner.Alert;15import org.parosproxy.paros.core.scanner.Category;16import org.parosproxy.paros.network.HttpMessage;17import org.zaproxy.zap.model.Vulnerabilities;18import org.zaproxy.zap.model.Vulnerability;19public class TestDomXSS extends AbstractDomAppPlugin 20{21 private static Vulnerability vuln = Vulnerabilities.getVulnerability("wasc_8");22 private static Logger log = Logger.getLogger(TestDomXSS.class);23 24 @Override25 public int getId() {26 return 10049;27 }28 @Override29 public String getName() {30 if (vuln != null) {31 return vuln.getAlert() + " (DOM Based)";32 }33 return "Cross Site Scripting (DOM Based)";34 }35 @Override36 public String[] getDependency() {37 return null;38 }39 @Override40 public String getDescription() {41 if (vuln != null) {42 return vuln.getDescription();43 }44 return "Failed to load vulnerability description from file";45 }46 @Override47 public int getCategory() {48 return Category.INJECTION;49 }50 @Override51 public String getSolution() {52 if (vuln != null) {53 return vuln.getSolution();54 }55 return "Failed to load vulnerability solution from file";56 }57 @Override58 public String getReference() {59 if (vuln != null) {60 StringBuilder sb = new StringBuilder();61 for (String ref : vuln.getReferences()) {62 if (sb.length() > 0) {63 sb.append('\n');64 }65 sb.append(ref);66 }67 return sb.toString();68 }69 return "Failed to load vulnerability reference from file";70 }71 @Override72 public void init() {73 }74 /* 75 @Override76 public void scan()77 { 78 79 }80 */ 81 private void scanHelper(WebDriver driver, String attackVector, String url) throws UnhandledAlertException82 {83 driver.get(url);84 List<WebElement> inputElements = driver.findElements(By.tagName("input"));85 //for(WebElement element : inputElements)86 for(int i = 0; i < inputElements.size(); i++)87 {88 //driver.get(url);89 WebElement element = inputElements.get(i);90 try91 {92 element.sendKeys(attackVector);93 element.click();94 }95 catch(UnhandledAlertException uae)96 {97 throw uae;98 }99 catch(WebDriverException wde)100 {101 log.debug(wde);102 }103 driver.get(url);104 inputElements = driver.findElements(By.tagName("input"));105 106 }107 List<WebElement>allElements = driver.findElements(By.tagName("div"));108 // for(WebElement element : allElements)109 for(int i = 0; i < allElements.size(); i++)110 {111 WebElement element = allElements.get(i);112 try113 {114 //driver.get(url);115 element.click();116 driver.get(url);117 allElements = driver.findElements(By.tagName("div"));118 }119 catch(UnhandledAlertException uae)120 {121 throw uae;122 }123 catch(ElementNotVisibleException enve)124 {125 log.debug(enve);126 }127 catch(WebDriverException wde)128 {129 log.debug(wde);130 }131 }132 }133 134 135 @Override136 public void scan(int source, ArrayList<WebDriver> drivers, String attackVector) throws UnhandledAlertException137 {138 HttpMessage msg = getBaseMsg();139 String url = msg.getRequestHeader().getURI().toString();140 String currURL = url + attackVector;141 WebDriver firefoxDriver = new FirefoxDriver();142 try143 {144 scanHelper(firefoxDriver, attackVector, currURL);145 }146 catch(UnhandledAlertException uae)147 {148 bingo(Alert.RISK_MEDIUM, Alert.RISK_MEDIUM, url, null, attackVector, "", currURL + " in Firefox ", msg);149 //return;150 throw uae;151 }152 finally153 {154 //firefoxDriver.close();155 firefoxDriver.quit();156 }157 if(System.getProperty("webdriver.chrome.driver") != null)158 {159 WebDriver chromeDriver = new ChromeDriver();160 try161 {162 scanHelper(chromeDriver, attackVector, currURL);163 }164 catch(UnhandledAlertException uae)165 {166 bingo(Alert.RISK_MEDIUM, Alert.RISK_MEDIUM, url, null, attackVector, "", currURL + " in Chrome ", msg);167 //return;168 throw uae;169 }170 finally171 {172 //chromeDriver.close();173 chromeDriver.quit();174 }175 }176 if(System.getProperty("webdriver.ie.driver") != null)177 {178 WebDriver ieDriver = new InternetExplorerDriver();179 try180 {181 scanHelper(ieDriver, attackVector, currURL);182 }183 catch(UnhandledAlertException uae)184 {185 bingo(Alert.RISK_MEDIUM, Alert.RISK_MEDIUM, url, null, attackVector, "", currURL + " in Internet Explorer ", msg);186 //return;187 throw uae;188 }189 finally190 {191 //ieDriver.close();192 ieDriver.quit();193 }194 }195 }196 /* public void scan(int source, WebDriver driver, String attackVector) throws UnhandledAlertException197 {198 HttpMessage msg = getBaseMsg();199 String url = msg.getRequestHeader().getURI().toString();200 String currURL = url + attackVector;201 try202 {203 scanHelper(driver, attackVector, currURL);204 }205 catch(UnhandledAlertException uae)206 {207 bingo(Alert.RISK_MEDIUM, Alert.RISK_MEDIUM, url, null, attackVector, "", currURL + driver.getClass().getCanonicalName(), msg);208 //return;209 throw uae;210 }211 finally212 {213 driver.close();214 }215 }216 */ 217 218 @Override219 public int getRisk() {...

Full Screen

Full Screen

Source:AbstractDomAppPlugin.java Github

copy

Full Screen

1package org.zaproxy.zap.extension.domxss;2import java.util.ArrayList;3import org.apache.log4j.Logger;4import org.openqa.selenium.UnhandledAlertException;5import org.openqa.selenium.WebDriver;6import org.openqa.selenium.chrome.ChromeDriver;7import org.openqa.selenium.firefox.FirefoxDriver;8import org.openqa.selenium.ie.InternetExplorerDriver;9import org.parosproxy.paros.core.scanner.AbstractAppPlugin;10public abstract class AbstractDomAppPlugin extends AbstractAppPlugin {11 private static Logger log = Logger.getLogger(AbstractDomAppPlugin.class);12 13 private static final int LOCATION_HASH = 0;14 private static final int LOCATION = 1;15 private static final int LOCATION_SEARCH = 2;16 private static final int REFERRER = 3;17 18 private static final int [] sources = {LOCATION_HASH, LOCATION, LOCATION_SEARCH, REFERRER};19 20 public static String [] locationHashAttackStrings = {21 "#alert(1)",//if eval sink22 "#<script>alert(1)</script>",23 "#<img src=\"random.gif\" onerror=alert(1)>",24 "#abc#<script>alert(1)</script>", // If document.write is the sink25 "#abc#<img src='random.gif' onerror=alert(1)",26 "#javascript:alert(1)"27 };28 29 public static String [] locationAttackStrings = {30 "#<script>alert(1)</script>",31 "?name=abc#<img src=\"random.gif\" onerror=alert(1)>",32 "#<img src=\"random.gif\" onerror=alert(1)>",33 };34 35 public static String [] locationSearchAttackStrings = {36 "?name=<img src=\"random.gif\" onerror=alert(1)>"37 };38 39 public static String [] referrerAttackStrings = {40 "?name=<img src=\"random.gif\" onerror=alert(1)>"41 };42 43 public static ArrayList<String[]> attackVectors;44 @Override45 public int getCategory() {46 // TODO Auto-generated method stub47 return 0;48 }49 @Override50 public String[] getDependency() {51 // TODO Auto-generated method stub52 return null;53 }54 @Override55 public String getDescription() {56 // TODO Auto-generated method stub57 return null;58 }59 @Override60 public int getId() {61 // TODO Auto-generated method stub62 return 0;63 }64 @Override65 public String getName() {66 // TODO Auto-generated method stub67 return null;68 }69 @Override70 public String getReference() {71 // TODO Auto-generated method stub72 return null;73 }74 @Override75 public String getSolution() {76 // TODO Auto-generated method stub77 return null;78 }79 @Override80 public void init() {81 // TODO Auto-generated method stub82 }83 @Override84 public void scan() {85 // TODO Auto-generated method stub86 attackVectors = new ArrayList<String[]>();87 attackVectors.add(locationHashAttackStrings);88 attackVectors.add(locationAttackStrings);89 attackVectors.add(locationSearchAttackStrings);90 attackVectors.add(referrerAttackStrings);91 92 for(int source : sources)93 {94 try95 {96 scan(source);97 }98 catch(UnhandledAlertException uae)99 {100 break;101 }102 }103 }104 105 public void scan(int source) throws UnhandledAlertException106 {107 for(String attackVector : attackVectors.get(source))108 {109 ArrayList<WebDriver> drivers = new ArrayList<WebDriver>();110 /* WebDriver firefoxDriver = new FirefoxDriver();111 drivers.add(firefoxDriver);112 try113 {114 WebDriver chromeDriver = new ChromeDriver();115 drivers.add(chromeDriver);116 }117 catch(IllegalStateException ise)118 {119 log.debug("Chrome Web Driver property is not set.", ise);120 }121 try122 {123 WebDriver ieDriver = new InternetExplorerDriver();124 drivers.add(ieDriver);125 }126 catch(IllegalStateException ise)127 {128 log.debug("Internet Explorer Web Driver property is not set.", ise);129 }*/130 try131 {132 scan(source, drivers, attackVector);133 }134 catch(UnhandledAlertException uae)135 {136 throw uae;137 }138 }139 }140 141 public void scan(int source, ArrayList<WebDriver> drivers, String attackVector) throws UnhandledAlertException142 {143/* for(int i = 0; i < drivers.size(); i++)144 {145 WebDriver driver = drivers.get(i);146 try147 {148 scan(source, driver, attackVector);149 }150 catch(UnhandledAlertException uae)151 {152 throw uae;153 154 }155 }156 */}157 /*158 public void scan(int source, WebDriver driver, String attackVector) throws UnhandledAlertException159 {160 161 }162 */163}...

Full Screen

Full Screen

Source:TimerPage.java Github

copy

Full Screen

...5import org.openqa.selenium.Alert;6import org.openqa.selenium.By;7import org.openqa.selenium.NoAlertPresentException;8import org.openqa.selenium.StaleElementReferenceException;9import org.openqa.selenium.UnhandledAlertException;10import org.openqa.selenium.WebDriver;11import org.openqa.selenium.WebElement;12import org.testng.Reporter;13public class TimerPage {14 WebDriver driver;15 public static Integer secondsCounter = 0;16 public static String before = null;17 public static String after = null;18 By countDownText = By.xpath("//p[@class='ClassicTimer-time']/span");19 20 //Timer Page Constructor21 public TimerPage(WebDriver driver) {22 this.driver = driver;23 }24 25 26 //Return Timer Page WebElements Countdown Text 27 public List<WebElement> countDownText()28 {29 return driver.findElements(countDownText);30 }31 32 // Function to check if Alert is Present33 public boolean isAlertPresent(WebDriver driver) 34 { 35 try 36 { 37 driver.switchTo().alert();38 Reporter.log("Alert Presence checked", true);39 return true; 40 } // try 41 catch (NoAlertPresentException Ex) 42 { 43 Reporter.log("Alert Presence checked",false);44 return false; 45 } // catch 46 47 48 } // isAlertPresent()49 50 51 //Function to validate the Timer Countdown52 public int[] validateTimerCountDown(long startTime) {53 54 int[] timer = new int[2];55 56 String pageSource = driver.getPageSource();57 // parse the page source through jsoup58 Document document = Jsoup.parse(pageSource);59 60 while(true){61 try { 62 if(countDownText().size()>1) { 63 after = countDownText().get(0).getText() + countDownText().get(1).getText(); 64 } else { 65 after = countDownText().get(0).getText(); 66 } 67 68 if(after.equalsIgnoreCase("Time Expired!")) {69 long endTime = System.currentTimeMillis() / 1000;70 System.out.println("End Time in Seconds:" + endTime); 71 int timeElapsed = (int) (endTime - startTime);72 timer[0] = timeElapsed;73 System.out.println("Time Elapsed:" + timeElapsed);74 break;75 }76 77 if(!after.equals(before)){78 System.out.println(after);79 before=after; 80 secondsCounter++; 81 } // End of If Loop 82 83 } catch(StaleElementReferenceException s) {84 try {85 System.out.println("Stale Element Encounter.Please Proceed with Countdown"); 86 } catch (UnhandledAlertException f) {87 try {88 Alert alert = driver.switchTo().alert();89 String alertText = alert.getText();90 System.out.println("Alert Text: " + alertText);91 alert.accept();92 } catch (NoAlertPresentException e) {93 e.printStackTrace();94 }95 } 96 } catch (UnhandledAlertException f) {97 handleAlert();98 } catch(IndexOutOfBoundsException i) {99 i.printStackTrace();100 } 101 } // End of While Loop 102 103 if(isAlertPresent(driver)) {104 handleAlert();105 } 106 107 timer[1] = secondsCounter;108 109 return timer; 110 ...

Full Screen

Full Screen

Source:AlertHandlingTest.java Github

copy

Full Screen

...18import org.junit.Test;19import org.openqa.selenium.Alert;20import org.openqa.selenium.By;21import org.openqa.selenium.NoAlertPresentException;22import org.openqa.selenium.UnhandledAlertException;23import org.openqa.selenium.support.ui.ExpectedConditions;24import org.openqa.selenium.support.ui.WebDriverWait;25public class AlertHandlingTest extends BaseAndroidTest {26 @Before27 public void setupWebView() {28 openWebdriverTestPage(HtmlTestData.ACTUAL_XHTML_PAGE);29 }30 @Test31 public void canHandleChainOfAlerts() {32 driver().executeScript("setTimeout(function(){alert(confirm('really? ' + prompt('testin alerts')));}, 100)");33 Alert a = new WebDriverWait(driver(), 2).until(ExpectedConditions.alertIsPresent());34 Assert.assertEquals("testin alerts", a.getText());35 a.sendKeys("WAT");36 a.accept();37 a = driver().switchTo().alert();38 Assert.assertEquals("really? WAT", a.getText());39 a.dismiss();40 a = driver().switchTo().alert();41 Assert.assertEquals("false", a.getText());42 a.dismiss();43 }44 @Test45 public void blocksOtherCallsWhenAlertPresent() {46 driver().executeScript("setTimeout(function(){alert('alert present');}, 100)");47 Alert a = new WebDriverWait(driver(), 2).until(ExpectedConditions.alertIsPresent());48 Assert.assertEquals("alert present", a.getText());49 try {50 driver().findElement(By.linkText("Foo"));51 throw new RuntimeException("should have gotten an UnhandledAlertException");52 } catch (UnhandledAlertException uae) {53 // pass54 } finally {55 a.accept();56 }57 }58 @Test59 public void alertNotPresentErrorOccurs() {60 try {61 driver().switchTo().alert();62 throw new RuntimeException("should have gotten an NoAlertPresentException");63 } catch (NoAlertPresentException nape) {64 }65 }66}...

Full Screen

Full Screen

Source:IWebDriver.java Github

copy

Full Screen

1package webdriver;2import org.openqa.selenium.By;3import org.openqa.selenium.NoSuchWindowException;4import org.openqa.selenium.TimeoutException;5import org.openqa.selenium.UnhandledAlertException;6import org.openqa.selenium.WebDriver;7import org.openqa.selenium.WebDriverException;8import org.openqa.selenium.WebElement;9import org.openqa.selenium.remote.UnreachableBrowserException;10/**11 * Interface for additional functions of the WebDriver.12 *13 * @author SpecOp014 */15public interface IWebDriver extends WebDriver {16 /**17 * Load the given page. Must handle all relevant exceptions.18 *19 * @param url URL to load.20 */21 void loadPage(String url);22 /**23 * By statement to get the child nodes.24 */25 By CHILD_NODES = By.xpath("./*");26 /**27 * By statement to get the parent element.28 */29 By PARENT_ELEMENT = By.xpath("..");30 /**31 * Get the parent element of given child.32 *33 * @param child child to get parent for.34 * @return Parent of the child.35 */36 static WebElement parentElement(WebElement child) {37 return child.findElement(PARENT_ELEMENT);38 }39 /**40 * Load the given page. Must handle all relevant exceptions.41 *42 * @param webDriver WebDriver to use.43 * @param url URL to load.44 */45 static void loadPage(IWebDriver webDriver, String url) {46 try {47 webDriver.get(url);48 } catch (TimeoutException ex) {49 System.out.println("timeout");50 } catch (UnhandledAlertException ex) {51 System.out.println("alert");52 } catch (UnreachableBrowserException | NoSuchWindowException ex) {53 System.out.println("unreachable or no such window");54 } catch (WebDriverException ex) {55 System.out.println("web driver exception");56 System.out.println(ex.toString());57 for (StackTraceElement element : ex.getStackTrace()) {58 System.out.println(element.toString());59 }60 }61 }62}...

Full Screen

Full Screen

Source:SeleniumUnExpectedDialogs.java Github

copy

Full Screen

1import java.util.List;2import org.openqa.selenium.Alert;3import org.openqa.selenium.By;4import org.openqa.selenium.UnexpectedAlertBehaviour;5import org.openqa.selenium.UnhandledAlertException;6import org.openqa.selenium.WebDriver;7import org.openqa.selenium.WebElement;8import org.openqa.selenium.chrome.ChromeDriver;9import org.openqa.selenium.interactions.Actions;10import org.openqa.selenium.remote.CapabilityType;11import org.openqa.selenium.remote.DesiredCapabilities;12public class SeleniumUnExpectedDialogs {13 public static void main(String[] args) {14 WebDriver driver = null;15 System.setProperty("webdriver.chrome.driver", "C:/chromedriver.exe");16 try {17 DesiredCapabilities chromeCapabilities = DesiredCapabilities.chrome();18 chromeCapabilities.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, 19 UnexpectedAlertBehaviour.ACCEPT);20 driver = new ChromeDriver(chromeCapabilities);21 driver.get("http://toolsqa.com/handling-alerts-using-selenium-webdriver/");22 driver.manage().window().maximize(); 23 List<WebElement> buttons = driver.findElements(By.tagName("button"));24 25 // handle alert26 new Actions(driver).moveToElement(buttons.get(0)).perform();27 buttons.get(0).click();28 driver.getCurrentUrl();29 30 31 System.out.println();32 33 } catch (UnhandledAlertException e) {34 System.out.println(e.getMessage());35 }36 finally {37 driver.close();38 driver.quit();39 }40 }41}...

Full Screen

Full Screen

Source:AlertHandling_Using_Try_Catch.java Github

copy

Full Screen

23import org.openqa.selenium.Alert;4import org.openqa.selenium.By;5import org.openqa.selenium.NoAlertPresentException;6import org.openqa.selenium.UnhandledAlertException;7import org.openqa.selenium.WebDriver;8import org.openqa.selenium.WebElement;9import org.openqa.selenium.chrome.ChromeDriver;1011public class AlertHandling_Using_Try_Catch 12{1314 public static void main(String[] args) throws Exception 15 {16 17 //browser initiation 18 System.setProperty("webdriver.chrome.driver", "chromedriver.exe");19 WebDriver driver=new ChromeDriver(); //launch browser20 driver.get("https://www.firstnaukri.com/"); //load url to browser window21 driver.manage().window().maximize(); //maximize browser window22 23 24 //Identify search button25 WebElement Search_btn=driver.findElement(By.xpath("//input[@value='Search']"));26 Search_btn.click();27 Thread.sleep(5000); //Timeout command28 29 30 try {31 32 //Switch to alert33 Alert alert=driver.switchTo().alert();34 35 //Capture text on alert window36 String alert_msg=alert.getText();37 System.out.println(alert_msg);38 39 //Close alert window40 alert.accept();41 42 43 } catch (NoAlertPresentException e) {44 e.printStackTrace();45 } catch (UnhandledAlertException e) {46 e.printStackTrace();47 }48 49 System.out.println("Script continued");50 51 52 53545556 }5758}

Full Screen

Full Screen

UnhandledAlertException

Using AI Code Generation

copy

Full Screen

1package com.seleniummaster.tutorial;2import org.openqa.selenium.Alert;3import org.openqa.selenium.By;4import org.openqa.selenium.WebDriver;5import org.openqa.selenium.WebElement;6import org.openqa.selenium.chrome.ChromeDriver;7import org.openqa.selenium.support.ui.ExpectedConditions;8import org.openqa.selenium.support.ui.WebDriverWait;9import org.testng.annotations.Test;10public class HandleAlertTest {11 public void testAlert() {12 System.setProperty("webdriver.chrome.driver", "c:\\webdriver\\chromedriver.exe");13 WebDriver driver = new ChromeDriver();14 driver.manage().window().maximize();15 driver.switchTo().frame("iframeResult");16 WebDriverWait wait = new WebDriverWait(driver, 10);17 Alert alert = driver.switchTo().alert();18 String alertMessage = alert.getText();19 System.out.println("Alert Message is: " + alertMessage);20 alert.dismiss();21 System.out.println("Result Message is: " + resultMessage.getText());22 driver.quit();23 }24}

Full Screen

Full Screen

UnhandledAlertException

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.Alert;2import org.openqa.selenium.By;3import org.openqa.selenium.WebDriver;4import org.openqa.selenium.WebElement;5import org.openqa.selenium.chrome.ChromeDriver;6import org.openqa.selenium.chrome.ChromeOptions;7import org.openqa.selenium.UnhandledAlertException;8import java.util.concurrent.TimeUnit;9public class HandlingAlerts {10 public static void main(String[] args) {11 System.setProperty("webdriver.chrome.driver", "C:\\Users\\HP\\Downloads\\chromedriver_win32\\chromedriver.exe");12 ChromeOptions options = new ChromeOptions();13 options.addArguments("--disable-notifications");14 WebDriver driver = new ChromeDriver(options);15 driver.manage().window().maximize();16 driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);17 driver.findElement(By.name("proceed")).click();18 try {19 Alert alert = driver.switchTo().alert();20 System.out.println(alert.getText());21 alert.accept();22 } catch (UnhandledAlertException e) {23 System.out.println("Alert not handled");24 }25 driver.findElement(By.id("login1")).sendKeys("hello");26 driver.findElement(By.id("password")).sendKeys("1234");27 driver.findElement(By.name("proceed")).click();28 try {29 Alert alert = driver.switchTo().alert();30 System.out.println(alert.getText());31 alert.dismiss();32 } catch (UnhandledAlertException e) {33 System.out.println("Alert not handled");34 }35 driver.quit();36 }37}

Full Screen

Full Screen

UnhandledAlertException

Using AI Code Generation

copy

Full Screen

1UnhandledAlertException objUnhandledAlertException = new UnhandledAlertException("Alert Message", "Alert Title");2objUnhandledAlertException.accept();3objUnhandledAlertException.dismiss();4String strAlertText = objUnhandledAlertException.getAlertText();5String strAlertTitle = objUnhandledAlertException.getAlertTitle();6UnhandledAlertException objUnhandledAlertException = new UnhandledAlertException("Alert Message", "Alert Title");7objUnhandledAlertException.accept();8objUnhandledAlertException.dismiss();9String strAlertText = objUnhandledAlertException.getAlertText();10String strAlertTitle = objUnhandledAlertException.getAlertTitle();11UnhandledAlertException objUnhandledAlertException = new UnhandledAlertException("Alert Message", "Alert Title");12objUnhandledAlertException.accept();13objUnhandledAlertException.dismiss();14String strAlertText = objUnhandledAlertException.getAlertText();15String strAlertTitle = objUnhandledAlertException.getAlertTitle();

Full Screen

Full Screen

Selenium 4 Tutorial:

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.

Chapters:

  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. 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.

  6. 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.

  7. 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.

Selenium 101 certifications:

LambdaTest also provides certification for Selenium testing to accelerate your career in Selenium automation testing.

Run Selenium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used methods in UnhandledAlertException

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful