Example usage for org.openqa.selenium WebDriver switchTo

List of usage examples for org.openqa.selenium WebDriver switchTo

Introduction

In this page you can find the example usage for org.openqa.selenium WebDriver switchTo.

Prototype

TargetLocator switchTo();

Source Link

Document

Send future commands to a different frame or window.

Usage

From source file:com.stratio.qa.specs.CommonG.java

License:Apache License

/**
 * Capture a snapshot or an evidence in the driver
 *
 * @param driver driver used for testing
 * @param type type//from  ww w. j  ava  2  s.c o m
 * @param suffix suffix
 * @return String
 */
public String captureEvidence(WebDriver driver, String type, String suffix) {
    String testSuffix = System.getProperty("TESTSUFFIX");
    String dir = "./target/executions/";
    if (testSuffix != null) {
        dir = dir + testSuffix + "/";
    }

    String clazz = ThreadProperty.get("class");
    String currentBrowser = ThreadProperty.get("browser");
    String currentData = ThreadProperty.get("dataSet");

    if (!currentData.equals("")) {
        currentData = currentData.replaceAll("[\\\\|\\/|\\|\\s|:|\\*]", "_");
    }

    if (!"".equals(currentData)) {
        currentData = "-" + HashUtils.doHash(currentData);
    }

    Timestamp ts = new Timestamp(new java.util.Date().getTime());
    String outputFile = dir + clazz + "/" + ThreadProperty.get("feature") + "." + ThreadProperty.get("scenario")
            + "/" + currentBrowser + currentData + ts.toString() + suffix;

    outputFile = outputFile.replaceAll(" ", "_");

    if (type.endsWith("htmlSource")) {
        if (type.equals("framehtmlSource")) {
            boolean isFrame = (Boolean) ((JavascriptExecutor) driver)
                    .executeScript("return window.top != window.self");

            if (isFrame) {
                outputFile = outputFile + "frame.html";
            } else {
                outputFile = "";
            }
        } else if (type.equals("htmlSource")) {
            driver.switchTo().defaultContent();
            outputFile = outputFile + ".html";
        }

        if (!outputFile.equals("")) {
            String source = ((RemoteWebDriver) driver).getPageSource();

            File fout = new File(outputFile);
            boolean dirs = fout.getParentFile().mkdirs();

            FileOutputStream fos;
            try {
                fos = new FileOutputStream(fout, true);
                Writer out = new OutputStreamWriter(fos, "UTF8");
                PrintWriter writer = new PrintWriter(out, false);
                writer.append(source);
                writer.close();
                out.close();
            } catch (IOException e) {
                logger.error("Exception on evidence capture", e);
            }
        }

    } else if ("screenCapture".equals(type)) {
        outputFile = outputFile + ".png";
        File file = null;
        driver.switchTo().defaultContent();
        ((Locatable) driver.findElement(By.tagName("body"))).getCoordinates().inViewPort();

        if (currentBrowser.startsWith("chrome") || currentBrowser.startsWith("droidemu")) {
            Actions actions = new Actions(driver);
            actions.keyDown(Keys.CONTROL).sendKeys(Keys.HOME).perform();
            actions.keyUp(Keys.CONTROL).perform();

            file = chromeFullScreenCapture(driver);
        } else {
            file = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        }
        try {
            FileUtils.copyFile(file, new File(outputFile));
        } catch (IOException e) {
            logger.error("Exception on copying browser screen capture", e);
        }
    }

    return outputFile;

}

From source file:com.stratio.qa.specs.CommonG.java

License:Apache License

private File chromeFullScreenCapture(WebDriver driver) {
    driver.switchTo().defaultContent();
    // scroll loop n times to get the whole page if browser is chrome
    ArrayList<File> capture = new ArrayList<File>();

    Boolean atBottom = false;//from   w  w w.j  a va2s.c om
    Integer windowSize = ((Long) ((JavascriptExecutor) driver)
            .executeScript("return document.documentElement.clientHeight")).intValue();

    Integer accuScroll = 0;
    Integer newTrailingImageHeight = 0;

    try {
        while (!atBottom) {

            Thread.sleep(DEFAULT_SLEEP_TIME);
            capture.add(((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE));

            ((JavascriptExecutor) driver)
                    .executeScript("if(window.screen)" + " {window.scrollBy(0," + windowSize + ");};");

            accuScroll += windowSize;
            if (getDocumentHeight(driver) <= accuScroll) {
                atBottom = true;
            }
        }

    } catch (InterruptedException e) {
        logger.error("Interrupted waits among scrolls", e);
    }

    newTrailingImageHeight = accuScroll - getDocumentHeight(driver);
    return adjustLastCapture(newTrailingImageHeight, capture);
}

From source file:com.synapticpath.naica.selenium.SeleniumOp.java

License:Open Source License

protected void processActionSuccess(Action action) {
    WebDriver driver = SeleniumTestContext.getInstance().getDriver();
    Iterator<String> iter = driver.getWindowHandles().iterator();
    String firstHandle = iter.next();
    String lastHandle = firstHandle;
    while (iter.hasNext()) {
        lastHandle = iter.next();/*from w  w  w  .j  av a2s .c om*/
    }
    if (!lastHandle.equals(firstHandle)) {
        driver.switchTo().window(lastHandle);
    }
}

From source file:com.thoughtworks.selenium.webdriven.commands.GetAllWindowNames.java

License:Apache License

@Override
protected String[] handleSeleneseCommand(WebDriver driver, String ignored, String alsoIgnored) {
    String current = driver.getWindowHandle();

    List<String> attributes = new ArrayList<>();
    for (String handle : driver.getWindowHandles()) {
        driver.switchTo().window(handle);
        attributes.add(((JavascriptExecutor) driver).executeScript("return window.name").toString());
    }//  w ww.  ja  v a  2 s. c  o m

    driver.switchTo().window(current);

    return attributes.toArray(new String[attributes.size()]);

}

From source file:com.thoughtworks.selenium.webdriven.commands.GetAllWindowTitles.java

License:Apache License

@Override
protected String[] handleSeleneseCommand(WebDriver driver, String ignored, String alsoIgnored) {
    String current = driver.getWindowHandle();

    List<String> attributes = new ArrayList<>();
    for (String handle : driver.getWindowHandles()) {
        driver.switchTo().window(handle);
        attributes.add(driver.getTitle());
    }// w ww  .j a  v a  2  s.c  om

    driver.switchTo().window(current);

    return attributes.toArray(new String[attributes.size()]);

}

From source file:com.thoughtworks.selenium.webdriven.commands.GetAttributeFromAllWindows.java

License:Apache License

@Override
protected String[] handleSeleneseCommand(WebDriver driver, String attributeName, String ignored) {
    String current = driver.getWindowHandle();

    List<String> attributes = new ArrayList<>();
    for (String handle : driver.getWindowHandles()) {
        driver.switchTo().window(handle);
        String value = (String) ((JavascriptExecutor) driver).executeScript("return '' + window[arguments[0]];",
                attributeName);/*from   w  w w  . j a  v  a  2  s  .  c  o  m*/
        attributes.add(value);
    }

    driver.switchTo().window(current);

    return attributes.toArray(new String[attributes.size()]);
}

From source file:com.thoughtworks.selenium.webdriven.commands.WaitForPopup.java

License:Apache License

@Override
protected Void handleSeleneseCommand(final WebDriver driver, final String windowID, final String timeout) {
    final long millis = toLong(timeout);
    final String current = driver.getWindowHandle();

    new Wait() {/* ww w .jav a  2  s. c om*/
        @Override
        public boolean until() {
            try {
                windows.selectPopUp(driver, windowID);
                return !"about:blank".equals(driver.getCurrentUrl());
            } catch (SeleniumException e) {
                // Swallow
            }
            return false;
        }
    }.wait(String.format("Timed out waiting for %s. Waited %s", windowID, timeout), millis);

    driver.switchTo().window(current);

    return null;
}

From source file:com.thoughtworks.selenium.webdriven.commands.Windows.java

License:Apache License

public void selectWindow(WebDriver driver, String windowID) {
    if (null == windowID || "null".equals(windowID) || "".equals(windowID)) {
        driver.switchTo().window(originalWindowHandle);
    } else if ("_blank".equals(windowID)) {
        selectBlankWindow(driver);// ww w.ja  va  2  s  .  c o m
    } else {
        if (windowID.startsWith("title=")) {
            selectWindowWithTitle(driver, windowID.substring("title=".length()));
            return;
        }

        if (windowID.startsWith("name=")) {
            windowID = windowID.substring("name=".length());
        }

        try {
            driver.switchTo().window(windowID);
        } catch (NoSuchWindowException e) {
            selectWindowWithTitle(driver, windowID);
        }
    }

    if (lastFrame.containsKey(driver.getWindowHandle())) {
        // If the frame has gone, fall back
        try {
            selectFrame(driver, lastFrame.get(driver.getWindowHandle()));
        } catch (SeleniumException e) {
            lastFrame.remove(driver.getWindowHandle());
        }
    }
}

From source file:com.thoughtworks.selenium.webdriven.commands.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.size() > 0) {
            driver.switchTo().window(windowHandles.iterator().next());
        } else {/*from   w  w w . j av a2s  .c  o m*/
            throw new SeleniumException("Unable to find a popup window");
        }
    } else {
        selectWindow(driver, windowID);
    }
}

From source file:com.thoughtworks.selenium.webdriven.commands.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;/*from   www.j  a va 2  s  . c  om*/
    }

    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);
    }
}