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.jboss.arquillian.graphene.context.TestGrapheneProxyHandler.java

License:Open Source License

@Test
public void test_webDriver_methods_which_should_return_proxy() {
    IsProxyable isProxyable = new IsProxyable();

    // when/*from  w  ww .j  a  v  a 2  s.c o m*/
    WebDriver driver = Mockito.mock(WebDriver.class, isProxyable);
    Options options = mock(Options.class, isProxyable);
    TargetLocator targetLocator = mock(TargetLocator.class, isProxyable);
    ImeHandler ime = mock(ImeHandler.class, isProxyable);
    Timeouts timeouts = mock(Timeouts.class, isProxyable);

    // then
    try {
        driver.manage();
        driver.navigate();
        driver.switchTo();
        driver.findElement(By.className(""));
        driver.findElements(By.className(""));
        driver.getWindowHandles();

        options.ime();
        options.logs();
        options.timeouts();
        options.window();
        options.getCookies();

        targetLocator.activeElement();
        targetLocator.alert();
        targetLocator.defaultContent();
        targetLocator.frame(0);
        targetLocator.frame("name");
        targetLocator.frame(mock(WebElement.class));
        targetLocator.window("name");

        ime.getAvailableEngines();

        timeouts.implicitlyWait(1L, TimeUnit.MICROSECONDS);
        timeouts.setScriptTimeout(1L, TimeUnit.MICROSECONDS);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    assertEquals(Arrays.asList(), isProxyable.getViolations());
}

From source file:org.jboss.arquillian.graphene.enricher.InFrameInterceptor.java

License:Open Source License

@Override
public Object intercept(InvocationContext context) throws Throwable {
    WebDriver browser = context.getGrapheneContext().getWebDriver();
    if (indexOfFrame != -1) {
        browser.switchTo().frame(indexOfFrame);
    } else if (nameOrIdOfFrame != null) {
        browser.switchTo().frame(nameOrIdOfFrame);
    }//from   w  w  w  .j  a v  a2  s. c  o m
    Object result = null;
    try {
        result = context.invoke();
    } finally {
        browser.switchTo().defaultContent();
    }
    if (result instanceof GrapheneProxyInstance) {
        ((GrapheneProxyInstance) result).registerInterceptor(this);
    }
    return result;
}

From source file:org.jitsi.meet.test.EtherpadTest.java

License:Apache License

/**
 * Write some text and check on the other side, whether the text
 * is visible./*from w w w . j  av a 2s.  c o  m*/
 */
public void writeTextAndCheck() {
    if (!enabled) {
        return;
    }

    System.err.println("Start writeTextAndCheck.");

    WebDriver owner = ConferenceFixture.getOwner();
    try {

        WebDriverWait wait = new WebDriverWait(owner, 30);
        wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.id("etherpadIFrame")));

        wait = new WebDriverWait(owner, 30);
        wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.name("ace_outer")));

        wait = new WebDriverWait(owner, 30);
        wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.name("ace_inner")));

        String textToEnter = "SomeTestText";

        owner.findElement(By.id("innerdocbody")).sendKeys(textToEnter);

        TestUtils.waitMillis(2000);

        // now search and check the text
        String txt = owner.findElement(By.xpath("//span[contains(@class, 'author')]")).getText();

        assertEquals("Texts do not match", textToEnter, txt);
    } finally {
        owner.switchTo().defaultContent();
    }
}

From source file:org.jitsi.meet.test.FilmstripOnlyTest.java

License:Apache License

/**
 * Checks if device selection popup can load.
 *//*from  ww w. j ava 2  s. com*/
@Test(dependsOnMethods = { "testLoadsOnlyTheFilmstrip" })
public void testDisplaysDeviceSelection() {
    getParticipant1().getToolbar().clickFilmstripOnlySettingsButton();

    // give some time for the window to open and load
    TestUtils.waitMillis(2000);

    WebDriver driver1 = getParticipant1().getDriver();

    Set<String> windowHandles = driver1.getWindowHandles();
    Iterator<String> handleIterator = windowHandles.iterator();
    String mainWindowHandle = handleIterator.next();
    String deviceSelectionHandle = handleIterator.next();

    driver1.switchTo().window(deviceSelectionHandle);

    // Ensure the device selection modal content is displayed.
    TestUtils.waitForDisplayedElementByXPath(driver1, "//div[contains(@class, 'device-selection')]", 5);

    driver1.close();
    driver1.switchTo().window(mainWindowHandle);
}

From source file:org.jitsi.meet.test.InviteTest.java

License:Apache License

/**
 * Checks if clicking to view more numbers shows the appropriate static
 * page.//  w  ww. jav a  2 s . c  o m
 */
@Test(dependsOnMethods = { "testDialInDisplays" })
public void testViewMoreNumbers() {
    InfoDialog infoDialog = participant.getInfoDialog();
    infoDialog.open();

    String displayedNumber = infoDialog.getDialInNumber();
    String displayedPin = infoDialog.getPinNumber();

    infoDialog.openDialInNumbersPage();

    // give some time for the window to open and load
    TestUtils.waitMillis(2000);

    WebDriver driver = participant.getDriver();

    ArrayList<String> tabs = new ArrayList<>(driver.getWindowHandles());
    driver.switchTo().window(tabs.get(1));

    DialInNumbersPage dialInNumbersPage = participant.getDialInNumbersPage();
    dialInNumbersPage.waitForLoad();

    String conferenceIDMessage = dialInNumbersPage.getConferenceIdMessage();

    assert (conferenceIDMessage.contains(displayedPin));
    assert (dialInNumbersPage.includesNumber(displayedNumber));

    driver.close();

    driver.switchTo().window(tabs.get(0));
}

From source file:org.jitsi.meet.test.SharedVideoTest.java

License:Apache License

/**
 * Start shared video./*from w w w  .  j a  v a 2  s  .co m*/
 * @param url
 * @param title
 * @param checkSecondParticipantState whether second participant state
 *                                    needs to be checked
 */
private void startSharingVideoByUrlAndTitle(String url, String title, boolean checkSecondParticipantState) {
    WebDriver owner = ConferenceFixture.getOwner();
    MeetUIUtils.clickOnToolbarButton(owner, "toolbar_button_sharedvideo");

    TestUtils.waitForElementByXPath(owner, "//input[@name='sharedVideoUrl']", 5);

    //owner.findElement(
    //    By.xpath("//input[@name='sharedVideoUrl']")).sendKeys(url);
    // sendKeys is not working for FF, seems the input has size of 20
    // and only 21 chars goes in, the size is not visible in
    // web-development console
    MeetUIUtils.setAttribute(owner, owner.findElement(By.xpath("//input[@name='sharedVideoUrl']")), "value",
            url);

    currentVideoTitle = title;

    owner.findElement(By.name("jqi_state0_buttonspandatai18ndialogShareSharespan")).click();

    WebDriverWait wait = new WebDriverWait(owner, 30);
    wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.id("sharedVideoIFrame")));
    // make sure we are in meet, not in the frame
    owner.switchTo().defaultContent();

    assertEquals("Video not displayed:", true, owner.findElement(By.id("sharedVideoIFrame")).isDisplayed());

    if (checkSecondParticipantState) {
        // Now let's check the second participant state
        WebDriver secondParticipant = ConferenceFixture.getSecondParticipant();
        // make sure we are in meet, not in the frame
        secondParticipant.switchTo().defaultContent();

        assertEquals("Video not displayed:", true,
                secondParticipant.findElement(By.id("sharedVideoIFrame")).isDisplayed());
    }
}

From source file:org.jitsi.meet.test.SharedVideoTest.java

License:Apache License

/**
 * Shares the video when only owner is in room, and if needed pause.
 * @param pause whether to pause before starting others
 *//*from w  w w . j  av a  2 s.c o m*/
private void shareVideoBeforeOthersJoin(boolean pause) {
    ConferenceFixture.closeAllParticipants();

    TestUtils.waitMillis(1000);

    WebDriver owner = ConferenceFixture.getOwner();

    MeetUtils.waitForParticipantToJoinMUC(owner, 10);
    TestUtils.waitForDisplayedElementByID(owner, "toolbar_button_sharedvideo", 10);

    // just wait a little after button is displayed
    // sometimes the button is reported as
    // Element is not clickable at point (566, -10)
    TestUtils.waitMillis(1000);

    startSharingVideoByUrlAndTitle(V2_LINK, V2_TITLE, false);
    checkPlayerLoadedAndInState(owner, "YT.PlayerState.PLAYING");

    String stateToCheck = "YT.PlayerState.PLAYING";
    if (pause) {
        stateToCheck = "YT.PlayerState.PAUSED";
        ((JavascriptExecutor) ConferenceFixture.getOwner())
                .executeScript(JS_GET_SHARED_VIDEO_CONTAINER + "c.player.seekTo(15);");
        ((JavascriptExecutor) ConferenceFixture.getOwner())
                .executeScript(JS_GET_SHARED_VIDEO_CONTAINER + "c.player.pauseVideo();");
    }

    ConferenceFixture.waitForSecondParticipantToConnect();
    MeetUtils.waitForIceConnected(owner);
    MeetUtils.waitForSendReceiveData(owner);

    // Now let's check the second participant state
    WebDriver secondParticipant = ConferenceFixture.getSecondParticipant();
    // make sure we are in meet, not in the frame
    secondParticipant.switchTo().defaultContent();

    checkPlayerLoadedAndInState(secondParticipant, stateToCheck);

    assertEquals("Video not displayed:", true,
            secondParticipant.findElement(By.id("sharedVideoIFrame")).isDisplayed());
}

From source file:org.julianharty.accessibility.automation.KeyboardHelpers.java

License:Apache License

/**
 * Uses the tab key to navigate around a web page.
 *
 * Helps determine which elements are reachable with the tab key and
 * whether the first active element can be reached again (indicating we
 * can 'loop' around the tabable elements on the page.
 *
 * Any iFrames are visited recursively.//from w w  w  .  j  av a2 s .co  m
 * 
 * A sample call follows:
 * <code><br/>
public void testTabbingThroughGoogleSearchResults() throws InterruptedException { <br/>
   FirefoxDriver driver = new FirefoxDriver(); <br/>
   driver.get("http://www.google.com/search?q=cheese"); <br/>
   int maxTabsToEnter = 300; <br/>
   int tabs = KeyboardHelpers.tabThroughWebPage(driver, maxTabsToEnter);<br/>
   assertTrue("Expected at least 50 tabs, only needed " + tabs, tabs > 50);<br/>
 } </code>
 *
 * @param driver a WebDriver connection with the target page loaded.
 * @param maxTabsToEnter the maximum tabs we should need to visit all the
 * tabable elements. Consider providing a 2x or 3x the expected number,
 * particularly for complex, unknown content.  
 * @return the number of tabs issued if the method reached an element that
 * matched the first active element, else -1 if it failed to complete
 * within the specified number of tabs. 
 * @throws InterruptedException if the call to sleep fails. 
 */
public static int tabThroughWebPage(WebDriver driver, int maxTabsToEnter) throws InterruptedException {

    WebElement firstElement = driver.switchTo().activeElement();
    WebElement currentElement = firstElement;
    currentSize = firstElement.getSize();

    int tabsIssued = 0;
    int iFrame = 0;
    String currentTagName = "(not set)";
    try {
        while (tabsIssued < (maxTabsToEnter)) {
            Point currentLocation = currentElement.getLocation();
            logDetailsOfWebElement(currentElement, currentLocation, tabsIssued);
            currentTagName = currentElement.getTagName();

            /*
             * for iframes switch to the iframe and call ourself recursively. We
             * think it always starts from _top of the iframe. That call will
             * tab until it 'falls out' of the active elements in the iframe.
             * Body will then be returned, then we need to switch back to the
             * parent.
             * 
             * Note: use periods to separate nested frames.
             */

            if (currentTagName.equals("iframe")) {
                driver.switchTo().frame(iFrame++);
                // A simple calculation to limit tabs in a 'broken' iFrame for now.
                tabThroughWebPage(driver, maxTabsToEnter - tabsIssued);
                // Will the following skip over the 'body' of the iFrame?
                driver.switchTo().defaultContent();
                currentElement = driver.switchTo().activeElement();
            }

            String currentTitle = getTitleOfCurrentElement(driver, currentElement);

            // Here is one of the termination conditions, if we find one of our titles.
            if (currentTitle.contains(TAB_KEYWORD + 0)) {
                logTerminationCondition(
                        String.format("Title %s of element matches the value set", currentTitle),
                        currentElement, tabsIssued);
                return tabsIssued;
            }

            setWebElementAttributesAsAppropriate(driver, currentElement, tabsIssued, currentTagName);

            currentElement.sendKeys(Keys.TAB); // "\t" also works
            tabsIssued++;
            // TODO 2011Aug16 Don't sleep with IE driver, it's too slow
            // Thread.sleep(500L);

            String previousTagName = currentTagName;
            Point previousLocation = currentLocation;
            Dimension previousSize = currentSize;
            currentElement = driver.switchTo().activeElement();
            currentLocation = currentElement.getLocation();
            currentSize = currentElement.getSize();
            currentTagName = currentElement.getTagName();

            /* Loop termination is still imprecise. Typically the first element
             * is the body element, however in some GWT applications it's a div
             * element for reasons I don't yet fathom. 
             * TODO(jharty): improve the precision and reliability of the 
             * matching as we learn more about how to interact with elements
             * on the page. 
             */

            if (GeneralHelpers.locationMatches(currentLocation, previousLocation)
                    && GeneralHelpers.dimensionsAreEqual(currentSize, previousSize)
                    && currentTagName.equals(previousTagName) && !currentTagName.equals("body")) {
                logTerminationCondition(String.format(
                        "Bad news: Element %s seems to match %s after tabbing. Are NativeEvents working?",
                        currentTagName, previousTagName), currentElement, tabsIssued);
                // Tell the user to check native events are working
                return -1;
            }

            if (currentElement.equals(firstElement) && tabsIssued >= 3) {
                logTerminationCondition("Current element matches first element", currentElement, tabsIssued);
                return tabsIssued;
            }
        }
    } catch (WebDriverException wde) {
        String innerHTML = (String) ((JavascriptExecutor) driver)
                .executeScript("return arguments[0].innerHTML;", currentElement);
        LOG.warning(String.format("Current Tag %s, InnerHTML for problem element is %s", currentTagName,
                innerHTML));
        throw wde;
    }
    return -1;
}

From source file:org.julianharty.accessibility.automation.LayoutAndOrdering.java

License:Apache License

private void tabLayoutTest(WebDriver driver) throws InterruptedException {
    WebElement bodyElement = driver.findElement(By.tagName("body"));
    WebElement firstElement = driver.switchTo().activeElement();
    WebElement currentElement = firstElement;
    Point preTabLocation = currentElement.getLocation();
    int tabsIssued = 0;
    while (tabsIssued < MAX_TABS) {
        // currentElement.sendKeys(Keys.CONTROL, Keys.ADD);
        currentElement.sendKeys(Keys.TAB); // "\t" also works
        tabsIssued++;// w w w .j av  a2s.com
        Thread.sleep(50L);
        currentElement = driver.switchTo().activeElement();
        currentElement.sendKeys(Keys.TAB);
        currentElement = driver.switchTo().activeElement();

        Point postTabLocation = currentElement.getLocation();
        System.out.println(GeneralHelpers.printElementLocations(tabsIssued, preTabLocation, postTabLocation));

        if (GeneralHelpers.locationMatches(postTabLocation, preTabLocation)) {
            // log termination condition;
            // Tell the user to check native events are working
            throw new InterruptedException("We don't seem to have moved, abandoning this test.");
        }
        if (currentElement.equals(firstElement)
                || currentElement.getLocation().equals(firstElement.getLocation())) {
            // Declare victory :)
            System.out.println("!!!!!! Yay!!!");
            return;
        }
        if (GeneralHelpers.compareElementLocationsForSaneTabOrder(preTabLocation, postTabLocation, tolerance)) {
            fail(GeneralHelpers.printElementLocations(tabsIssued, preTabLocation, postTabLocation));
        }
        preTabLocation = postTabLocation;

    }
}

From source file:org.kuali.khr.hub.util.Helper.java

License:Educational Community License

public static void switchFrame(String framename, WebDriver driver) {
    WebElement frame = driver.findElement(By.xpath("//*[contains(@name, '" + framename + "')]"));
    String frameID = frame.getAttribute("name");
    driver.switchTo().frame(frameID);
}