List of usage examples for org.openqa.selenium WebDriver switchTo
TargetLocator switchTo();
From source file:com.thoughtworks.selenium.webdriven.commands.Windows.java
License:Apache License
private void selectWindowWithTitle(WebDriver driver, String title) { String current = driver.getWindowHandle(); for (String handle : driver.getWindowHandles()) { driver.switchTo().window(handle); if (title.equals(driver.getTitle())) { return; }/*from w w w . j a v a2 s . com*/ } driver.switchTo().window(current); throw new SeleniumException("Unable to select window with title: " + title); }
From source file:com.thoughtworks.selenium.webdriven.commands.Windows.java
License:Apache License
/** * Selects the only <code>_blank</code> window. A window open with <code>target='_blank'</code> * will have a <code>window.name = null</code>. * <p/>/*from w ww .ja v a 2 s. com*/ * <p> * This method assumes that there will only be one single <code>_blank</code> window and selects * the first one with no name. Therefore if for any reasons there are multiple windows with * <code>window.name = null</code> the first found one will be selected. * <p/> * <p> * If none of the windows have <code>window.name = null</code> the last selected one will be * re-selected and a {@link SeleniumException} will be thrown. * * @throws NoSuchWindowException if no window with <code>window.name = null</code> is found. */ public void selectBlankWindow(WebDriver driver) { String current = driver.getWindowHandle(); // Find the first window without a "name" attribute List<String> handles = new ArrayList<String>(driver.getWindowHandles()); for (String handle : handles) { // the original window will never be a _blank window, so don't even look at it // this is also important to skip, because the original/root window won't have // a name either, so if we didn't know better we might think it's a _blank popup! if (handle.equals(originalWindowHandle)) { continue; } driver.switchTo().window(handle); String value = (String) ((JavascriptExecutor) driver).executeScript("return window.name;"); if (value == null || "".equals(value)) { // We found it! return; } } // We couldn't find it driver.switchTo().window(current); throw new SeleniumException("Unable to select window _blank"); }
From source file:com.thoughtworks.selenium.webdriven.Windows.java
License:Apache License
public void selectPopUp(WebDriver driver, String windowID) { if ("null".equals(windowID) || "".equals(windowID)) { Set<String> windowHandles = driver.getWindowHandles(); windowHandles.remove(originalWindowHandle); if (!windowHandles.isEmpty()) { driver.switchTo().window(windowHandles.iterator().next()); } else {//www.j a va 2 s . co m throw new SeleniumException("Unable to find a popup window"); } } else { selectWindow(driver, windowID); } }
From source file:com.thoughtworks.selenium.webdriven.Windows.java
License:Apache License
public void selectFrame(WebDriver driver, String locator) { if ("relative=top".equals(locator)) { driver.switchTo().defaultContent(); lastFrame.remove(driver.getWindowHandle()); return;/* ww w . j a va2s. com*/ } if ("relative=up".equals(locator)) { driver.switchTo().parentFrame(); lastFrame.put(driver.getWindowHandle(), locator); return; } if (locator.startsWith("index=")) { try { int index = Integer.parseInt(locator.substring("index=".length())); lastFrame.put(driver.getWindowHandle(), locator); driver.switchTo().frame(index); return; } catch (NumberFormatException e) { throw new SeleniumException(e.getMessage(), e); } catch (NoSuchFrameException e) { throw new SeleniumException(e.getMessage(), e); } } if (locator.startsWith("id=")) { locator = locator.substring("id=".length()); } else if (locator.startsWith("name=")) { locator = locator.substring("name=".length()); } try { lastFrame.put(driver.getWindowHandle(), locator); driver.switchTo().frame(locator); } catch (NoSuchFrameException e) { throw new SeleniumException(e.getMessage(), e); } }
From source file:com.vaadin.testbench.TestBenchDriverTest.java
@Test public void testTestBenchDriverActsAsProxy() { FirefoxDriver mockDriver = createMock(FirefoxDriver.class); mockDriver.close();//from ww w . ja v a 2 s . c o m expectLastCall().once(); WebElement mockElement = createNiceMock(WebElement.class); expect(mockDriver.findElement(isA(By.class))).andReturn(mockElement); List<WebElement> elements = Arrays.asList(mockElement); expect(mockDriver.findElements(isA(By.class))).andReturn(elements); mockDriver.get("foo"); expectLastCall().once(); expect(mockDriver.getCurrentUrl()).andReturn("foo"); expect(mockDriver.getPageSource()).andReturn("<html></html>"); expect(mockDriver.getTitle()).andReturn("bar"); expect(mockDriver.getWindowHandle()).andReturn("baz"); Set<String> handles = new HashSet<String>(); expect(mockDriver.getWindowHandles()).andReturn(handles); Options mockOptions = createNiceMock(Options.class); expect(mockDriver.manage()).andReturn(mockOptions); Navigation mockNavigation = createNiceMock(Navigation.class); expect(mockDriver.navigate()).andReturn(mockNavigation); mockDriver.quit(); expectLastCall().once(); expect(((JavascriptExecutor) mockDriver).executeScript(anyObject(String.class))).andStubReturn(true); TargetLocator mockTargetLocator = createNiceMock(TargetLocator.class); expect(mockDriver.switchTo()).andReturn(mockTargetLocator); replay(mockDriver); // TestBenchDriverProxy driver = new TestBenchDriverProxy(mockDriver); WebDriver driver = TestBench.createDriver(mockDriver); driver.close(); By mockBy = createNiceMock(By.class); assertTrue(driver.findElement(mockBy) instanceof TestBenchElementCommands); assertTrue(driver.findElements(mockBy).get(0) instanceof TestBenchElementCommands); driver.get("foo"); assertEquals("foo", driver.getCurrentUrl()); assertEquals("<html></html>", driver.getPageSource()); assertEquals("bar", driver.getTitle()); assertEquals("baz", driver.getWindowHandle()); assertEquals(handles, driver.getWindowHandles()); assertEquals(mockOptions, driver.manage()); assertEquals(mockNavigation, driver.navigate()); driver.quit(); assertEquals(mockTargetLocator, driver.switchTo()); verify(mockDriver); }
From source file:com.virtusa.isq.vtaf.runtime.SeleniumTestBase.java
License:Apache License
/** * Opens an URL in a new test frame. This accepts both relative and absolute * URLs. The "open" command <br>/*from w ww . jav a 2 s . co m*/ * waits for the page to load before proceeding, ie. the "AndWait" suffix is * implicit. Note: The URL <br> * must be on the same domain as the runner HTML due to security * restrictions in the browser <br> * (Same Origin Policy). If you need to open an URL on another domain, use * the Selenium Server <br> * to start a new browser session on that domain. * * @param locator * the locator * @param waitTime * the wait time */ private void doNavigateToURL(final ObjectLocator locator, final String waitTime) { String url = ""; WebDriver driver = getDriver(); try { url = locator.getActualLocator(); setCommandStartTime(getCurrentTime()); if (url.toLowerCase(Locale.getDefault()).startsWith("openwindow=")) { Set<String> oldWindowHandles = getAllWindows(); String actualUrl = url.substring(url.indexOf('=') + 1, url.length()); JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("window.open('" + actualUrl + "', '_newWindow');"); super.sleep(Integer.parseInt(waitTime)); Set<String> newWindowHandles = getAllWindows(); newWindowHandles.removeAll(oldWindowHandles); Object[] newWindowArr = newWindowHandles.toArray(); driver.switchTo().window(newWindowArr[0].toString()); } else { driver.get(url); super.sleep(Integer.parseInt(waitTime)); } reportresult(true, "NAVIGATE TO URL Command :" + url + "", "PASSED", url); } catch (Exception e) { String errorString = e.getMessage(); reportresult(true, "NAVIGATE TO URL :" + url + "", "FAILED", "NAVIGATE TO URL command : URL " + url + " failed. Actual Error : " + errorString); checkTrue(false, true, "NAVIGATE TO URL command : URL " + url + " failed. Actual Error : " + errorString); } }
From source file:com.virtusa.isq.vtaf.runtime.SeleniumTestBase.java
License:Apache License
/** * Arguments: <br>/* w ww .j a va 2 s . co m*/ * <br> * * windowID - the JavaScript window ID of the window to select<br> * * Selects a popup window using a window locator; once a popup window has * been selected, all commands go to that window. To select the main window * again, use null as the target.<br> * <br> * * Window locators provide different ways of specifying the window object: * by title, by internal JavaScript "name," or by JavaScript variable.<br> * <br> * * title=My Special Window: Finds the window using the text that appears in * the title bar. Be careful; two windows can share the same title. If that * happens, this locator will just pick one.<br> * name=myWindow: Finds the window using its internal JavaScript "name" * property. This is the second parameter "windowName" passed to the * JavaScript method window.open(url, windowName, windowFeatures, * replaceFlag) (which Selenium intercepts).<br> * var=variableName: Some pop-up windows are unnamed (anonymous), but are * associated with a JavaScript variable name in the current application * window, e.g. "window.foo = window.open(url);". In those cases, you can * open the window using "var=foo".<br> * <br> * * If no window locator prefix is provided, we'll try to guess what you mean * like this:<br> * <br> * * 1.) if windowID is null, (or the string "null") then it is assumed the * user is referring to the original window instantiated by the browser).<br> * <br> * * 2.) if the value of the "windowID" parameter is a JavaScript variable * name in the current application window, then it is assumed that this * variable contains the return value from a call to the JavaScript * window.open() method.<br> * <br> * * 3.) Otherwise, selenium looks in a hash it maintains that maps string * names to window "names".<br> * <br> * * 4.) If that fails, we'll try looping over all of the known windows to try * to find the appropriate "title". Since "title" is not necessarily unique, * this may have unexpected behavior.<br> * <br> * * If you're having trouble figuring out the name of a window that you want * to manipulate, look at the Selenium log messages which identify the names * of windows created via window.open (and therefore intercepted by * Selenium). You will see messages like the following for each window as it * is opened:<br> * <br> * * debug: window.open call intercepted; window ID (which you can use with * selectWindow()) is "myNewWindow"<br> * <br> * * In some cases, Selenium will be unable to intercept a call to window.open * (if the call occurs during or before the "onLoad" event, for example). * (This is bug SEL-339.) In those cases, you can force Selenium to notice * the open window's name by using the Selenium openWindow command, using an * empty (blank) url, like this: openWindow("", "myFunnyWindow").<br> * <br> * * @param locator * : Logical name of the window assigned by the test scriptor * * * */ private void doSelectWindow(final ObjectLocator locator) { int counter = getRetryCount(); String targetWindow = null; WebDriver driver = getDriver(); // Getting the actual object identification from the object map String window = locator.getActualLocator(); try { checkForNewWindowPopups(); /* * START DESCRIPTION following for loop was added to make the * command more consistent try the command for give amount of time * (can be configured through class variable RETRY) command will be * tried for "RETRY" amount of times or untill command works. any * exception thrown within the tries will be handled internally. * * can be exited from the loop under 2 conditions 1. if the command * succeeded 2. if the RETRY count is exceeded */ while (counter > 0) { try { counter--; targetWindow = getMatchingWindowFromCurrentWindowHandles(driver, window); if (targetWindow != null) { driver.switchTo().window(targetWindow); driver.manage().window().maximize(); focusToCurrentWindow(driver); reportresult(true, "SELECT WINDOW :" + locator.getLogicalName() + "", "PASSED", ""); break; } else { throw new WebDriverException("Window Not Found" + window); } } catch (WebDriverException ex) { sleep(retryInterval); if (!(counter > 0)) { String errorString = ex.getMessage(); String objectName = locator.getLogicalName(); reportresult(true, "SELECT WINDOW :" + objectName + "", "FAILED", "selectWindow command :Element (" + objectName + ") [" + window + "] is not accessible. Actual Error : " + errorString); checkTrue(false, true, "selectWindow command :Element (" + objectName + ") [" + window + "] is not accessible. Actual Error : " + errorString); } } } } catch (Exception e) { e.printStackTrace(); String objectName = locator.getLogicalName(); // if any exception is raised, report failure reportresult(true, "SELECT WINDOW :" + objectName + "", "FAILED", "selectWindow command :Element (" + objectName + ") [" + window + "] not present"); checkTrue(false, true, "selectWindow command :Element (" + objectName + ") [" + window + "] not present"); } }
From source file:com.virtusa.isq.vtaf.runtime.SeleniumTestBase.java
License:Apache License
/** * Gets the matching window from current window handles. * // w ww .j av a2s .com * @param driver * the driver * @param inputWindowName * the input window name * @return the matching window from current window handles * @throws Exception * the exception */ private String getMatchingWindowFromCurrentWindowHandles(final WebDriver driver, final String inputWindowName) throws Exception { String targetWindow = null; Set<String> windowarr = getAllWindows(); if (inputWindowName.startsWith("index=")) { int winIndex = Integer.parseInt( inputWindowName.substring(inputWindowName.indexOf('=') + 1, inputWindowName.length())); targetWindow = getOpenWindowHandleIndex().get(winIndex); } else { boolean objectFound = false; for (String windowname : windowarr) { if (inputWindowName.startsWith("regexp:") || inputWindowName.startsWith("glob:")) { objectFound = isMatchingPattern( inputWindowName.substring(inputWindowName.indexOf(':') + 1, inputWindowName.length()), driver.switchTo().window(windowname).getTitle()); } else if (driver.switchTo().window(windowname).getTitle().equals(inputWindowName)) { objectFound = true; } if (objectFound) { targetWindow = windowname; break; } } } return targetWindow; }
From source file:com.virtusa.isq.vtaf.runtime.SeleniumTestBase.java
License:Apache License
/** * Handle popup.// w w w . j a va 2s.co m * * @param actionFlow * the action flow * @param waitTime * the wait time * @throws Exception * the exception */ public final void handlePopup(final String actionFlow, final String waitTime) throws Exception { initRobot(); clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); this.inputStringp = actionFlow; this.waitTimep = waitTime; Thread newThread = new Thread(new Runnable() { @Override public void run() { try { sleep(Integer.parseInt(waitTimep)); } catch (Exception e1) { e1.printStackTrace(); } if (inputStringp.startsWith("FORCE%")) { forceHandlePopup(getRobot(), inputStringp.split("%")[1]); reportresult(true, "HANDLE POPUP :" + inputStringp + "", "PASSED", ""); } else { /* * If the popup is not a forcrfully handled it will be * handled in the normal way */ String verificationErrors = ""; String actualAlertText = ""; WebDriver driver = getDriver(); String[] commands = inputStringp.split("\\|"); try { actualAlertText = driver.switchTo().alert().getText(); } catch (NoAlertPresentException e) { reportresult(true, "HANDLE POPUP : failed. No Alert Present", "FAILED", ""); checkTrue(false, true, "HANDLE POPUP : failed. No Alert Present"); } verificationErrors = executeHandlePopupCommands(driver, commands, actualAlertText); if (verificationErrors.isEmpty()) { reportresult(true, "HANDLE POPUP :" + actualAlertText + "", "PASSED", ""); } else { reportresult(true, "HANDLE POPUP : failed", "FAILED", "Errors : " + verificationErrors + ""); checkTrue(false, false, "HANDLE POPUP : failed. Errors : " + verificationErrors + ""); } } } } ); newThread.start(); }
From source file:com.virtusa.isq.vtaf.runtime.SeleniumTestBase.java
License:Apache License
/** * Execute handle popup commands./*from ww w .j a v a 2 s . co m*/ * * @param driver * the driver * @param commands * the commands * @param actualAlertText * the actual alert text * @return the string */ private String executeHandlePopupCommands(final WebDriver driver, final String[] commands, final String actualAlertText) { StringBuilder verificationErrorBuilder = new StringBuilder(); boolean isPopupHandled = false; for (String command : commands) { String commandString = command.toLowerCase(Locale.getDefault()); if (commandString.startsWith("type=")) { String typeStr = command.substring(command.indexOf('=') + 1, command.length()); driver.switchTo().alert().sendKeys(typeStr); } else if (commandString.startsWith("verify=")) { String verifyStr = command.substring(command.indexOf('=') + 1, command.length()); if (!verifyStr.equals(actualAlertText)) { verificationErrorBuilder.append("VERIFY TEXT failed. Actual : " + "" + actualAlertText + " Expected : " + verifyStr + " "); } } else if (commandString.startsWith("action=")) { String actionStr = command.substring(command.indexOf('=') + 1, command.length()); if ("ok".equalsIgnoreCase(actionStr)) { driver.switchTo().alert().accept(); isPopupHandled = true; } else if ("cancel".equalsIgnoreCase(actionStr)) { driver.switchTo().alert().dismiss(); isPopupHandled = true; } } else { verificationErrorBuilder.append("Handle Popup command failed. Given input command (" + command + ")is not recognized. Supported commands : type, verify, action."); } } if (!isPopupHandled) { driver.switchTo().alert().accept(); isPopupHandled = true; } return verificationErrorBuilder.toString(); }