// Q: what happens if I send text to alert? // A: ElementNotVisibleException in Firefox // A: in Chrome the text is sent @Test public void basicAlertHandlingKeysTest() { WebElement alertButton; WebElement alertResult; alertButton = driver.findElement(By.id("alertexamples")); alertButton.click(); String alertMessage = "I am an alert box!"; assertEquals(alertMessage, driver.switchTo().alert().getText()); if (Driver.currentDriver == Driver.BrowserName.FIREFOX) { try { driver.switchTo().alert().sendKeys("Hello keys Accept"); fail("expected a ElementNotVisibleException thrown"); } catch (ElementNotVisibleException e) { assertTrue("Expected to get an exception", true); } } if (Driver.currentDriver == Driver.BrowserName.GOOGLECHROME) { // chrome seems happy to send in text to an alert driver.switchTo().alert().sendKeys("Hello keys Accept"); } driver.switchTo().alert().accept(); }
@Test(expected = NoSuchElementException.class) public void shouldBeAbleToClickInAFrame() throws InterruptedException { WebDriver d = getDriver(); d.get("http://docs.wpm.neustar.biz/testscript-api/index.html"); assertEquals("__MAIN_FRAME__", getCurrentFrameName(d)); d.switchTo().frame("classFrame"); assertEquals("classFrame", getCurrentFrameName(d)); // This should cause a reload in the frame "classFrame" d.findElement(By.linkText("HttpClient")).click(); // Wait for new content to load in the frame. WebDriverWait wait = new WebDriverWait(d, 10); wait.until(ExpectedConditions.titleContains("HttpClient")); // Frame should still be "classFrame" assertEquals("classFrame", getCurrentFrameName(d)); // Check if a link "clearCookies()" is there where expected assertEquals("clearCookies", d.findElement(By.linkText("clearCookies")).getText()); // Make sure it was really frame "classFrame" which was replaced: // 1. move to the other frame "packageFrame" d.switchTo().defaultContent().switchTo().frame("packageFrame"); assertEquals("packageFrame", getCurrentFrameName(d)); // 2. the link "clearCookies()" shouldn't be there anymore d.findElement(By.linkText("clearCookies")); }
@Test public void test() throws InterruptedException { // Alert popup Handling. driver.findElement(By.xpath("input[@value='Show Me Alert']")).click(); // To locate alert Alert A1 = driver.switchTo().alert(); // To read the text from alert popup. String Alert1 = A1.getText(); System.out.println(Alert1); Thread.sleep(2000); // To accept/Click OK on the alert popup A1.accept(); // Confirmation Pop up handling. driver.findElement(By.xpath("//button[@onlick='myFunction()']")).click(); Alert A2 = driver.switchTo().alert(); String Alert2 = A2.getText(); System.out.println(Alert2); Thread.sleep(2000); // To Click on cancel button of confirmation box. A2.dismiss(); // Prompt pop up handling. driver.findElement(By.xpath("//button[contains(.,'Show Me Prompt')]")).click(); Alert A3 = driver.switchTo().alert(); String Alert3 = A3.getText(); System.out.println(Alert3); // To type text Im text box of prompt pop up. A3.sendKeys("This is John"); Thread.sleep(2000); A3.accept(); }
@Then("^틴캐시 결제수단 한도 알럿이 노출된다$") public void 틴캐시_결제수단_한도_알럿이_노출된다() throws Throwable { // Assert.assertTrue(driver.getTitle().contains("//*[@id='error_msg_desc1']")); String parentWindowId = driver.getWindowHandle(); Set<String> allWindows = driver.getWindowHandles(); if (!allWindows.isEmpty()) { for (String windowID : allWindows) { driver.switchTo().window(windowID); if (driver.getPageSource().contains("확인해주세요")) { try { WebElement noMoreButton = driver.findElement(By.xpath("//*[@id='errorPopup1']")); noMoreButton.click(); WebElement identifyButton = driver.findElement(By.xpath("//*[@id='errorPopup1']/div/p/a/img")); identifyButton.click(); break; } catch (NoSuchWindowException e) { e.printStackTrace(); } } } } driver.switchTo().window(parentWindowId); }
@Test public void workWithTheIFrame() { driver.get("http://www.compendiumdev.co.uk/selenium/frames"); WebDriverWait wait = new WebDriverWait(driver, Driver.DEFAULT_TIMEOUT_SECONDS); assertThat(driver.getTitle(), is("Frameset Example Title (Example 6)")); // click on "menu"."iFrames Example" driver.switchTo().frame("menu"); driver.findElement(By.cssSelector("a[href='iframe.html']")).click(); wait.until(titleIs("HTML Frames Example - iFrame Contents")); // click on Example 5 in the iFrame driver.switchTo().frame(0); driver.findElement(By.cssSelector("a[href='frames_example_5.html']")).click(); wait.until(titleIs("Frameset Example Title (Example 5)")); // then content.load main frames page driver.switchTo().frame("content"); driver.findElement(By.cssSelector("a[href='index.html']")).click(); wait.until(titleIs("Frameset Example Title (Example 6)")); }
@Test public void testUntitled() throws Exception { login.testUntitled(); JavascriptExecutor js = (JavascriptExecutor) driver; driver.findElement(By.cssSelector("a[id=itemMM50]")).click(); driver.findElement(By.cssSelector("div[id=mmSUB117]")).click(); js.executeScript( "chamaItemMenu('/citsmart/pages/dinamicViews/dinamicViews.load?identificacao=ReqSLA')"); Thread.sleep(2000L); driver.findElement(By.cssSelector("span.combo-arrow.combo-arrow-hover")).click(); driver.findElement(By.cssSelector("input.combo-text.validatebox-text")).clear(); driver.findElement(By.cssSelector("input.combo-text.validatebox-text")).sendKeys("layanne"); driver.findElement(By.cssSelector("div.datagrid-cell.datagrid-cell-c3-NOME")).click(); driver.findElement(By.id("REQUISITADOEM")).click(); driver.findElement(By.cssSelector("span.ui-icon.ui-icon-circle-triangle-e")).click(); driver.findElement(By.cssSelector("span.ui-icon.ui-icon-circle-triangle-e")).click(); driver.findElement(By.cssSelector("span.ui-icon.ui-icon-circle-triangle-e")).click(); driver.findElement(By.linkText("18")).click(); driver.findElement(By.id("ASSUNTO")).clear(); driver.findElement(By.id("ASSUNTO")).sendKeys("teste"); driver.findElement(By.id("DETALHAMENTO")).clear(); driver.findElement(By.id("DETALHAMENTO")).sendKeys("teste"); driver.findElement(By.id("btnGravar")).click(); driver.switchTo().alert().getText().endsWith("Registro inserido com sucesso"); Thread.sleep(2000L); driver.switchTo().alert().accept(); }
// ClientArchive public static void ClientArchive() throws InterruptedException { WebDriver driver = StaticClass.driver; loginapp(driver); Thread.sleep(5000); System.out.println("ClientArchive initiated"); driver.findElement(By.xpath(".//*[@id='sidebar']/ul/li[5]/a/span")).click(); driver.findElement(By.xpath(".//*[@id='sidebar']/ul/li[5]/ul/li[1]/a")).click(); Thread.sleep(3000); driver.findElement(By.xpath(".//*[@id='sidebar']/ul/li[5]/ul/li[1]/ul/li[2]/a")).click(); Thread.sleep(5000); driver.findElement(By.xpath("//a[contains(@href,'ArchiveClient.aspx?ID=3')]")).click(); Thread.sleep(3000); String parentwindow = driver.getWindowHandle(); for (String Child_Window : driver.getWindowHandles()) { driver.switchTo().window(Child_Window); } driver.findElement(By.xpath(".//*[@id='btnClose']")).click(); Thread.sleep(5000); driver.switchTo().window(parentwindow); Thread.sleep(5000); System.out.println("ClientArchive completed"); }
/** * Finds handle to second window other than given handle to current window and switches to as * well. * * @param handleCurrentWindow * @return handleSecondWindow */ public String findAndSwitchToSecondWindow(String handleCurrentWindow) { pause(1000); Set<String> windows = driver.getWindowHandles(); String handleSecondWindow = null; for (String window : windows) { if (!window.contains(handleCurrentWindow)) { handleSecondWindow = window; } } // Switch to the second window. try { pause(2000); driver.switchTo().window(handleSecondWindow); } catch (Throwable failure) { // If there is problem in switching // window, then re-try. pause(1000); driver.switchTo().window(handleSecondWindow); } return handleSecondWindow; }
public void iframe() { driver.get("http://www.magicbricks.com"); // driver.switchTo().frame(10); // iframe count from top driver.switchTo().frame("wkStorageFrame"); // iframe's id System.out.println( driver.findElement(By.xpath("/html/body")).getText()); // o/p: This is the storage Frame driver.switchTo().defaultContent(); // to bring back from iframe to main // window }
@Test public void testAlert() { driver.get("http://localhost:1234/2014/09/06/Alert.html"); driver.findElement(By.className("button")).click(); driver.switchTo().alert().accept(); driver.findElement(By.className("button")).click(); System.out.println(driver.switchTo().alert().getText()); driver.switchTo().alert().dismiss(); }
public static void main(String[] args) throws InterruptedException { System.setProperty( "webdriver.chrome.driver", "C:\\Users\\jakther\\Desktop\\jahed\\java\\chromedriver\\chromedriver.exe"); driver = new ChromeDriver(); driver.get("https://test.salesforce.com"); Thread.sleep(2000); driver.findElement(By.id("username")).sendKeys("*****@*****.**"); driver.findElement(By.id("password")).sendKeys("06082003Tuba"); driver.findElement(By.id("Login")).click(); Thread.sleep(2000); driver.findElement(By.id("Account_Tab")).click(); Thread.sleep(2000); List<WebElement> list = driver.findElements(By.cssSelector(".dataCell>a")); System.out.println(list.size()); for (int i = 0; i < list.size(); i++) { WebElement ele = driver.findElement( By.xpath( ".//*[@id='bodyCell']/div[3]/div[1]/div/div[2]/table/tbody/tr[" + (i + 2) + "]/th/a")); System.out.println(ele.getText()); switch (ele.getText()) { case "MD J Akther": ele.click(); Thread.sleep(2000); driver.findElement(By.xpath(".//*[@id='topButtonRow']/input[4]")).click(); Thread.sleep(2000); try { Alert alert = driver.switchTo().alert(); alert.accept(); Thread.sleep(2000); } catch (Exception e) { } break; case "Akther Nabil": ele.click(); Thread.sleep(2000); driver.findElement(By.xpath(".//*[@id='topButtonRow']/input[4]")).click(); Thread.sleep(2000); try { Alert alert = driver.switchTo().alert(); alert.accept(); Thread.sleep(2000); } catch (Exception e) { } break; default: } } }
/** * Returns the text of the message * * @return Text of the message */ public String getText() { String window = driver.getWindowHandle(); WebElement iframe = driver.findElement(By.tagName("iframe")); driver.switchTo().frame(iframe); WebElement iframeBody = driver.findElement(By.xpath("html/body")); String text = iframeBody.getText(); driver.switchTo().window(window); return text; }
@Test public void verify_message() { driver.findElement(By.xpath("//input[@name='userid']")).sendKeys("UID1"); driver.findElement(By.xpath("//input[@type='password']")).sendKeys("pass1"); driver.findElement(By.xpath("//input[@value='Login']")).click(); String alert = driver.switchTo().alert().getText(); driver.switchTo().alert().accept(); Assert.assertEquals("UserId Is : UID1 Password Is : pass1", alert); System.out.println("Alert Is Fine."); }
@Test public void titleShouldReturnWindowTitle() { WebDriver d = getDriver(); d.get("http://docs.wpm.neustar.biz/testscript-api/index.html"); assertEquals("__MAIN_FRAME__", getCurrentFrameName(d)); String topLevelTitle = d.getTitle(); d.switchTo().frame("packageFrame"); assertEquals("packageFrame", getCurrentFrameName(d)); assertEquals(topLevelTitle, d.getTitle()); d.switchTo().defaultContent(); assertEquals(topLevelTitle, d.getTitle()); }
@Test public void switchToFrameByElement() { WebDriver d = getDriver(); d.get("http://docs.wpm.neustar.biz/testscript-api/index.html"); assertEquals("__MAIN_FRAME__", getCurrentFrameName(d)); d.switchTo().frame(d.findElement(By.name("packageFrame"))); assertEquals("packageFrame", getCurrentFrameName(d)); d.switchTo().defaultContent(); assertEquals("__MAIN_FRAME__", getCurrentFrameName(d)); d.switchTo().frame(d.findElement(By.name("packageFrame"))); assertEquals("packageFrame", getCurrentFrameName(d)); }
public static void main(String[] args) { InternetExplorerVar ieVar = new InternetExplorerVar(); LoggingIn.doItHere(ieVar); WebDriver driver = ieVar.getDriver(); WebElement element; driver.get(ieVar.getBaseURL() + "/pages/setup/department/department_list.aspx"); element = driver.findElement(By.id("key")); element.clear(); element.sendKeys(new String[] {"ANDRPRGR"}); element = driver.findElement(By.id("filter")); element.clear(); element.sendKeys(new String[] {"Andrey\'s Providers"}); element = driver.findElement(By.id("search_btn")); element.click(); for (int i = 0; true; i++) { try { Thread.sleep(5); } catch (InterruptedException e) { continue; } if (i == 200) { return; } try { element = driver.findElement(By.xpath("//div[@id=\'list_list_body\']/div/div")); element.click(); } catch (NoSuchElementException e) { continue; } catch (StaleElementReferenceException e) { continue; } catch (ElementNotVisibleException e) { continue; } catch (TimeoutException e) { i = 0; continue; } break; } String parentWindowHandler = driver.getWindowHandle(); element = driver.findElement(By.id("list_delete_button")); element.click(); try { while (true) { driver.switchTo().alert().accept(); } } catch (NoAlertPresentException e) { } driver.switchTo().window(parentWindowHandler); Logout.doItHere(ieVar); }
private void enterContent(String pageContent) { WebElement tinymceEditor = null; WebElement textEditor = null; try { driver.switchTo().frame(driver.findElement(By.id("content_ifr"))); tinymceEditor = driver.findElement(By.id("tinymce")); } catch (Exception e) { textEditor = driver.findElement(By.id("content")); } WebElement editor = tinymceEditor != null ? tinymceEditor : textEditor; editor.sendKeys(pageContent); if (tinymceEditor != null) { driver.switchTo().defaultContent(); } }
@Test public void basicAlertHandlingDismissTest() { WebElement alertButton; alertButton = driver.findElement(By.id("alertexamples")); alertButton.click(); String alertMessage = "I am an alert box!"; assertEquals(alertMessage, driver.switchTo().alert().getText()); driver.switchTo().alert().dismiss(); }
protected void checkAlert() { try { Alert alert = driver.switchTo().alert(); alert.accept(); } catch (Exception e) { } }
/** * Enter title and text * * @param title * @param text */ public void enterBasicMessageData(String title, String text) { WebElement titleField = driver.findElement(By.id("j_idt39:headline")); titleField.clear(); titleField.sendKeys(title); String window = driver.getWindowHandle(); WebElement iframe = driver.findElement(By.tagName("iframe")); driver.switchTo().frame(iframe); WebElement iframeBody = driver.findElement(By.xpath("html/body")); // As the editor does not use a textfield but the body of a iframe, we are not able to call // clear() // so we select the existing text and replace it with the new text. iframeBody.sendKeys(Keys.chord(Keys.CONTROL, "a")); iframeBody.sendKeys(text); driver.switchTo().window(window); }
@Test public void clickConfirmUsingSelenium() { WebDriver driver = new ChromeDriver(); driver.get("http://localhost:63342/seleniumcapsules/html/upload.html"); driver.findElement(cssSelector("input[value='Need Confirm']")).click(); driver.switchTo().alert().accept(); }
public static Point getFramePoint(WebDriver webDriver) { int x = 0; int y = 0; WebElement bodyWebElement = getWebElement(webDriver, "//body"); WrapsDriver wrapsDriver = (WrapsDriver) bodyWebElement; WebDriver wrappedWebDriver = wrapsDriver.getWrappedDriver(); WebDriver.TargetLocator targetLocator = wrappedWebDriver.switchTo(); targetLocator.window(_defaultWindowHandle); for (WebElement webElement : _frameWebElements) { Point point = webElement.getLocation(); x += point.getX(); y += point.getY(); targetLocator.frame(webElement); } return new Point(x, y); }
// 走审批流程 // @Test(dependsOnMethods = { "apply" }) public void doApproval() { try { while (!quitFlowFlag) { login(apl.getLoginName(), apl.getPassWord()); doDaiban(); dr.switchTo().defaultContent(); dr.switchTo().frame(1); if (apl.getRole().equals("proManger")) { doProManger(); login("baoj_lz", "1"); locate(); // return; } else { // 提交下一步 ((JavascriptExecutor) dr).executeScript("isAuditOperate = true;dosubmit()"); Thread.sleep(1000); getNext(); // 获得提交下一处理信息 confirmNext(); logout(); } } } catch (Exception e) { e.printStackTrace(); } }
/** @param window Handle to window */ public void switchWindow(int window) { try { driver.switchTo().window(getWindowHandles(5)[window]); } catch (Exception e) { log.error("An ERROR ocured when trying to switch window: " + e); } }
/** * Switch to desired Frame * * @param frame */ public void switchToFrame(int frameNumber) { try { driver.switchTo().frame(frameNumber); } catch (Exception e) { log.error("An ERROR ocured when trying to switch frame: " + e); } }
protected File savePageSourceToFile(String fileName, WebDriver webdriver, boolean retryIfAlert) { File pageSource = new File(reportsFolder, fileName + ".html"); try { writeToFile(webdriver.getPageSource(), pageSource); } catch (UnhandledAlertException e) { if (retryIfAlert) { try { Alert alert = webdriver.switchTo().alert(); log.severe(e + ": " + alert.getText()); alert.accept(); savePageSourceToFile(fileName, webdriver, false); } catch (Exception unableToCloseAlert) { log.severe("Failed to close alert: " + unableToCloseAlert); } } else { printOnce("savePageSourceToFile", e); } } catch (UnreachableBrowserException e) { writeToFile(e.toString(), pageSource); return pageSource; } catch (Exception e) { writeToFile(e.toString(), pageSource); printOnce("savePageSourceToFile", e); } return pageSource; }
@Test public void basicPromptConfirmHandlingAcceptTest() { WebElement promptButton; WebElement promptResult; promptButton = driver.findElement(By.id("promptexample")); promptResult = driver.findElement(By.id("promptreturn")); assertEquals("pret", promptResult.getText()); promptButton.click(); String alertMessage = "I prompt you"; Alert promptAlert = driver.switchTo().alert(); if (Driver.currentDriver != Driver.BrowserName.IE) { // no point doing this in IE as we know it isn't the actual prompt assertEquals(alertMessage, promptAlert.getText()); } promptAlert.accept(); assertEquals("change me", promptResult.getText()); }
@Test public static void main(String[] args) throws InterruptedException { WebDriver driver = new FirefoxDriver(); driver.get("http://www.spicejet.com/"); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); driver.findElement(By.id("ctl00_mainContent_rbtnl_Trip_1")).click(); driver.findElement(By.id("ctl00_mainContent_ddl_originStation1_CTXT")).click(); driver.findElement(By.linkText("Hyderabad (HYD)")).click(); Thread.sleep(1000); driver.findElement(By.linkText("Delhi (DEL)")).click(); driver .findElement(By.xpath("//table[@class='ui-datepicker-calendar']/tbody/tr[4]/td[6]/a")) .click(); driver.findElement(By.id("ctl00_mainContent_btn_FindFlights")).click(); String mainwindow = driver.getWindowHandle(); driver.findElement(By.id("popUpConverter")).click(); Set<String> allwindows = driver.getWindowHandles(); for (String child : allwindows) { if (child.equals(allwindows)) { System.out.println("Don't switch"); } else { driver.switchTo().window(child); // System.out.println(child); /*Thread.sleep(10000); //driver.manage().window().maximize(); driver.findElement(By.id("CurrencyConverterCurrencyConverterView_TextBoxAmount")).sendKeys("10000"); driver.switchTo().defaultContent();*/ } } }
@Test public void basicPromptConfirmHandlingDismissTest() { WebElement promptButton; WebElement promptResult; promptButton = driver.findElement(By.id("promptexample")); promptResult = driver.findElement(By.id("promptreturn")); assertEquals("pret", promptResult.getText()); promptButton.click(); String alertMessage = "I prompt you"; Alert promptAlert = driver.switchTo().alert(); if (Driver.currentDriver == Driver.BrowserName.IE) { // In IE the alert always returns "Script Prompt:" and not the // actual prompt text, so this line is just to alert me if the // functionality changes if (!promptAlert.getText().equals("Script Prompt:")) { throw new RuntimeException("IE now does not do Script Prompt"); } } else { // only check the alert prompt if not in IE assertEquals(alertMessage, promptAlert.getText()); } promptAlert.dismiss(); assertEquals("pret", promptResult.getText()); }
/** * Workaround for Webdriver issue 1438 (http://code.google.com/p/selenium/issues/detail?id=1438) */ private void ensureValidDriver() { try { proxiedWebDriver.getCurrentUrl(); } catch (WebDriverException e) { proxiedWebDriver.switchTo().defaultContent(); } }