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:org.safs.selenium.SeleniumGUIUtilities.java

License:Open Source License

/**
 * selects a window to send future commands to
 * @param selenium Current Selenium object
 * @param id windowId--can be null/*from  w w  w.ja va 2s.  c  om*/
 * @param timeout how long to wait for the window in seconds
 * @return whether window was found
 */
public boolean selectWindow(Selenium selenium, String id, long timeout) {

    // workaround Selenium.selectWindow deadlock defect
    //
    ThreadedSelectWindow selectWindow = new ThreadedSelectWindow(Thread.currentThread(), selenium, id, timeout);
    try {
        selectWindow.start();
        Thread.sleep((timeout * 1000) + 1000); //backup timeout for deadlocks
    } catch (Exception e) {
    }
    if (selectWindow.isSearching()) {
        Log.debug("SGU: selectWindow thread may have deadlocked after " + selectWindow.searchSeconds()
                + " seconds.");
    }
    // hasten cleanup
    boolean found = selectWindow.isSelected();
    selectWindow = null;

    if (!found) {
        WebDriver driver = null;
        try {
            if (selenium instanceof com.thoughtworks.selenium.webdriven.WebDriverBackedSelenium) {
                //WebDriver driver = ((WebDriverBackedSelenium) selenium).getUnderlyingWebDriver();
                driver = ((com.thoughtworks.selenium.webdriven.WebDriverBackedSelenium) selenium)
                        .getWrappedDriver();
            }
        } catch (Throwable noclass) {
            Log.debug(
                    "SGU: selectWindow handling older selenium install " + noclass.getClass().getSimpleName());
            /** WebDriverBackedSelenium version 37 move to com.thoughtworks.selenium.webdriven in 42 selenium version
            try{
               if(selenium instanceof org.openqa.selenium.WebDriverBackedSelenium){
                  driver = ((org.openqa.selenium.WebDriverBackedSelenium) selenium).getWrappedDriver();
               }
            }catch(Throwable ignore){
               Log.debug("SGU: selectWindow ignoring newer selenium install "+ ignore.getClass().getSimpleName());
            }
            **/
        }
        if (driver != null) {
            driver.switchTo().window(driver.getWindowHandle());
            found = true;
        }
    }

    Log.info("SGU: selectWindow found window? " + found);
    return found;
}

From source file:org.safs.selenium.webdriver.DCDriverCommand.java

License:Open Source License

/**
 * TODO Need to move to class WDLibrary, this doesn't work yet!!!
 * @param webdriver/*from   w ww  .j  a v  a  2 s. co  m*/
 * @throws SeleniumPlusException
 */
static void focusWindow(WebDriver webdriver) throws SeleniumPlusException {
    try {
        org.openqa.selenium.Point position = webdriver.manage().window().getPosition();
        org.openqa.selenium.Dimension dim = webdriver.manage().window().getSize();
        webdriver.manage().window().maximize();
        webdriver.manage().window().setPosition(position);
        webdriver.manage().window().setSize(dim);
        webdriver.switchTo().window(webdriver.getWindowHandle());
        WDLibrary.executeScript("window.focus();");
    } catch (Exception e) {
        throw new SeleniumPlusException("Failed to minimize current browser window" + e.getMessage());
    }
}

From source file:org.safs.selenium.webdriver.lib.SearchObject.java

License:Open Source License

private static boolean _switchFrame(WebDriver webdriver, WebElement frame) {
    if (webdriver == null || frame == null)
        return false;
    String debugmsg = StringUtils.debugmsg(false);

    try {//from   www. j a  v  a 2  s.c  om
        webdriver.switchTo().frame(frame);
        IndependantLog.debug(debugmsg + " switched to frame '" + frame + "'");
        return true;
    } catch (Exception e) {
        IndependantLog.debug(
                debugmsg + " failed to switch to frame '" + frame + "' due to " + StringUtils.debugmsg(e));
        return false;
    }
}

From source file:org.safs.selenium.webdriver.lib.SearchObject.java

License:Open Source License

/** 
 * Before doing any component search, we make sure we are in the correct frame.  
 * Frame information may or may not be within the provided recognition string.
 * @param recognitionString//from  w  w w .j av  a2s .com
 */
protected static SwitchFramesResults _switchFrames(String recognitionString) {
    String debugmsg = StringUtils.debugmsg(SearchObject.class, "_swithcFrames");

    String[] st = StringUtils.getTokenArray(recognitionString, childSeparator, escapeChar);
    /* rsWithoutFrames: Recognition String may contain some Frame-RS, after handling the
     * frames, these Frame-RS are no longer useful, so they will be removed and the rest
     * RS will be kept in the list rsWithoutFrames
     */
    List<String> rsWithoutFrames = new ArrayList<String>();
    TargetLocator targetLocator = null;
    boolean haveSwichedFrame = false;

    //1. Handle the Frames Recognition String
    try {
        WebDriver webdriver = getWebDriver();
        lastVisitedURL = webdriver.getCurrentUrl();
        targetLocator = webdriver.switchTo();
        //very IMPORTANT step: Switch back to the top window or first frame
        targetLocator.defaultContent();
        boolean done = false;
        boolean retried = false;
        while (!done) {

            //Get information about the browser window by "javascript code",
            //as Selenium window object doesn't provide enough information.
            Window window = webdriver.manage().window();
            Object windowObject = BrowserWindow.getWindowObjectByJS(window);
            if (windowObject != null) {
                try {
                    lastBrowserWindow = new BrowserWindow(windowObject);
                    IndependantLog.debug(
                            debugmsg + " DOM window Object retrieved successfully.  Evaluating information...");
                } catch (Exception e) {
                    IndependantLog.warn(debugmsg + e.getMessage());
                    if (lastBrowserWindow == null) {
                        IndependantLog.error(
                                debugmsg + " lastBrowserWindow is null, create a default BrowserWindow.");
                        lastBrowserWindow = new BrowserWindow();
                    } else {
                        IndependantLog.debug(debugmsg + "Retaining the last Browser window object instead.");
                    }
                }
                done = true;
            } else {
                // CANAGL -- resolving problems in IE after "Login"
                // DEBUG Experimental -- IE not working the same as other browsers
                IndependantLog.debug(debugmsg + " DOM window Object could not be retrieved.");
                if (!retried) {
                    IndependantLog.debug(debugmsg + " retrying a new targetLocator WebDriver...");
                    webdriver = reconnectLastWebDriver();

                    IndependantLog.debug(debugmsg + " changing the last visited URL from '" + lastVisitedURL
                            + "' to '" + webdriver.getCurrentUrl() + "'");
                    lastVisitedURL = webdriver.getCurrentUrl();

                    targetLocator = webdriver.switchTo();
                    targetLocator.defaultContent();
                    retried = true;
                } else {
                    IndependantLog.debug(debugmsg + " retrying a new targetLocator FAILED.");
                    done = true;
                    throw new SeleniumPlusException(
                            "Suspected UnreachableBrowserException seeking Browser DOM window Object.");
                }
            }
        }

        //reset the frame before searching the frame element if it exists.
        FrameElement frameElement = null;
        WebElement frame = null;
        String frameRS = null;
        //search the frame element if RS contains frame-info
        for (String rst : st) {
            //pre-check if this RS contains anything about frame-RS
            frameRS = retrieveFrameRS(rst);

            if (frameRS != null) {
                //Get frame WebElement according to frame's recognition string
                frame = _getSwitchFrame(webdriver, frameRS);
                if (frame != null) {
                    frameElement = new FrameElement(frameElement, frame);
                    haveSwichedFrame = _switchFrame(webdriver, frame);

                    //Can we use frame as SearchContext for child frame? FrameID=parentFrame;\;FrameID=childFrame
                    //NO, frame WebElement can NOT be used as SearchContext, will cause Exception
                    //We should always use webdriver as the SearchContext to find frame WebElement

                    //don't break, if there is frame in frame, as FRAMENAME=parent;\\;FRAMENAME=child
                    //break;
                }

            } else {
                //IndependantLog.warn(debugmsg+" store normal recognition string '"+rst+"' for further processing.");
                rsWithoutFrames.add(rst);
            }
        }

        if (haveSwichedFrame)
            lastFrame = frameElement;

    } catch (Exception e) {
        IndependantLog.error(debugmsg + " during switching frame, met exception " + StringUtils.debugmsg(e));
    }

    //2. Before search an element, switch to the correct frame
    //   For the child component, we don't need to specify the frame-RS, they use the same frame-RS as
    //   their parent component.
    try {
        if (!haveSwichedFrame && targetLocator != null) {
            FrameElement frameElement = lastFrame;
            Stack<FrameElement> frameStack = new Stack<FrameElement>();
            while (frameElement != null) {
                frameStack.push(frameElement);
                frameElement = frameElement.getParentFrame();
            }
            while (!frameStack.isEmpty() && frameStack.peek() != null) {
                targetLocator.frame(frameStack.pop().getWebElement());
                haveSwichedFrame = true;
            }
        }
    } catch (Exception e) {
        if (e instanceof StaleElementReferenceException && pageHasChanged()) {
            IndependantLog.warn(
                    debugmsg + " switching to the previous frame 'lastFrame' failed! The page has changed!");
            //LeiWang: S1215754
            //if we click a link within a FRAME, as the link is in a FRAME, so the field 'lastFrame' will be assigned after clicking the link.
            //then the link will lead us to a second page, when we try to find something on that page, firstly we try to switch to 'lastFrame' and
            //get a StaleElementReferenceException (as we are in the second page, there is no such frame of the first page)
            //but we still want our program to find the web-element on the second page, so we will just set 'lastFrame' to null and let program continue.
            //            [FirstPage]
            //            FirstPage="FRAMEID=iframeResult"
            //            Link="xpath=/html/body/a"
            //
            //            [SecondPage]
            //            SecondPage="xpath=/html"
            //            return null;
        } else {
            IndependantLog.warn(debugmsg + " switching to the previous frame 'lastFrame' failed! Met exception "
                    + StringUtils.debugmsg(e));
        }
        //LeiWang: S1215778
        //If we fail to switch to 'lastFrame', which perhaps means that it is not useful anymore
        //we should reset it to null, otherwise it will cause errors, such as calculate the element's screen location
        IndependantLog.debug(debugmsg + " 'lastFrame' is not useful anymore, reset it to null.");
        lastFrame = null;
    }
    return new SwitchFramesResults().setRsWithoutFrames(rsWithoutFrames).setSwitchedFrames(haveSwichedFrame);
}

From source file:org.safs.selenium.webdriver.lib.WDLibrary.java

License:Open Source License

/**
 * Wait for the presence of Alert-Modal-Dialog associated with a certain browser identified by ID.<br>
 * It will get the cached webdriver according to the browser's id, and get the 'alert' through that webdriver.<br>
 * <b>Note:</b>This API will NOT change the current WebDriver. {@link #getWebDriver()} will still return the same object.<br>
 * // w ww.  j  av a2  s  .  c  o  m
 * @param optionals String...
 * <ul>
 * <b>optionals[0] timeoutWaitAlertPresence</b> int, timeout in seconds to wait for the presence of Alert.
 *                                                   If not provided, default is 2 seconds.<br>
 *                                                   If it is provided as {@link #TIMEOUT_NOWAIT}, this method will try to get Alert without waiting.<br>
 * <b>optionals[1] browserID</b> String, the ID to get the browser on which the 'alert' will be closed.
 *                                       If not provided, the current browser will be used.<br>
 * </ul>
 * @return Alert, the current Alert on browser; it could be null if it is not present within timeout.
 * @throws SeleniumPlusException, if WebDriver cannot be got according to the parameter browserID.<br>
 *                                if Alert is not present within timeout.<br>
 */
private static Alert waitAlert(String... optionals) throws SeleniumPlusException {
    String debugmsg = StringUtils.debugmsg(false);
    String browserID = null;
    int timeout = timeoutWaitAlert;
    Alert alert = null;

    if (optionals != null && optionals.length > 0) {
        if (StringUtils.isValid(optionals[0])) {
            try {
                timeout = Integer.parseInt(optionals[0]);
            } catch (NumberFormatException e) {
            }
        }
        if (optionals.length > 1 && StringUtils.isValid(optionals[1]))
            browserID = optionals[1];
    }

    WebDriver webdriver = getWebDriver(browserID);

    if (webdriver == null) {
        throw new SeleniumPlusException("cannot get webdriver according to id '" + browserID + "'",
                SeleniumPlusException.CODE_OBJECT_IS_NULL);
    }

    try {
        if (timeout == TIMEOUT_NOWAIT) {
            alert = webdriver.switchTo().alert();//NoAlertPresentException
        } else {
            WebDriverWait wait = new WebDriverWait(webdriver, timeout);
            alert = wait.until(ExpectedConditions.alertIsPresent());//TimeoutException
        }

        return alert;
    } catch (Exception e) {
        String message = "Fail to get alert dialog associated with "
                + (browserID == null ? "current browser." : "browser '" + browserID + "'.");
        IndependantLog.warn(debugmsg + message + " due to " + StringUtils.debugmsg(e));
        throw new SeleniumPlusException(message);
    }
}

From source file:org.specrunner.webdriver.AbstractPluginSwitchTo.java

License:Open Source License

@Override
protected void doEnd(IContext context, IResultSet result, WebDriver client) throws PluginException {
    doEnd(context, result, client, client.switchTo());
}

From source file:org.specrunner.webdriver.actions.switchto.PluginFrameOn.java

License:Open Source License

@Override
protected void process(IContext context, IResultSet result, WebDriver client, WebElement element)
        throws PluginException {
    client.switchTo().frame(element);
    result.addResult(Success.INSTANCE, context.peek());
}

From source file:org.suren.autotest.web.framework.invoker.EngineInvoker.java

License:Apache License

/**
 * urlwindow//  ww  w.ja va  2s  . co  m
 * @param phoenix 
 * @param params ?
 */
public static void closeWinByUrlStartWith(Phoenix phoenix, String[] params) {
    String startWith = params[0];
    WebDriver driver = phoenix.getEngine().getDriver();
    Set<String> handles = driver.getWindowHandles();
    Iterator<String> handleIt = handles.iterator();

    String currentHandle = driver.getWindowHandle();
    while (handleIt.hasNext()) {
        String handle = handleIt.next();

        driver.switchTo().window(handle);

        if (driver.getCurrentUrl().startsWith(startWith)) {
            driver.close();
            break;
        }
    }

    driver.switchTo().window(currentHandle);
}

From source file:org.suren.autotest.web.framework.invoker.EngineInvoker.java

License:Apache License

/**
 * window??/*from w ww  .j a va 2 s .c om*/
 * @param phoenix 
 */
public static void windowSwitch(Phoenix phoenix) {
    SeleniumEngine engine = phoenix.getEngine();
    WebDriver driver = engine.getDriver();
    Set<String> handlers = driver.getWindowHandles();
    Iterator<String> it = handlers.iterator();
    while (it.hasNext()) {
        String name = it.next();

        driver.switchTo().window(name);
    }
}

From source file:org.vige.rubia.selenium.forum.action.CreatePost.java

License:Apache License

public static String createPost(WebDriver driver, Post post) {
    WebElement home = driver.findElement(linkText(HOME_LINK));
    home.click();/*from   w w w. j a va 2 s .c o  m*/
    WebElement forumEl = driver.findElement(linkText(post.getTopic().getForum().getName()));
    forumEl.click();
    WebElement topicSubject = driver.findElement(linkText(post.getTopic().getSubject()));
    topicSubject.click();
    WebElement bodyText = driver.findElement(className(REPLY_POST_BUTTON)).findElement(xpath("a[2]"));
    bodyText.click();
    switchFrame(driver);
    WebElement bodytInput = driver.findElement(cssSelector("body"));
    bodytInput.sendKeys(post.getMessage().getText());
    driver.switchTo().defaultContent();
    addAttachments(driver, post);
    WebElement operationButton = driver.findElement(id(SUBMIT_BUTTON));
    operationButton.click();
    WebElement resultCreatePost = driver
            .findElement(xpath("//td[contains(@class,forumpostcontent)]/p[contains(text(),'"
                    + post.getMessage().getText() + "')]"));
    String updatedPost = resultCreatePost.getText();
    return updatedPost;
}