Java Code Examples for org.openqa.selenium.WebDriver#getWindowHandle()

The following examples show how to use org.openqa.selenium.WebDriver#getWindowHandle() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PageSteps.java    From vividus with Apache License 2.0 7 votes vote down vote up
/**
 * Closes <b>current window</b> and switches to the window from which rederection to current window was performed
 * <p>
 * Each browser <b>window</b> or <b>tab</b> is considered to be a separate <b>window object</b>. This object holds
 * corresponding <b>Document</b> object, which itself is a html page. So this method applies to both windows and
 * tabs.
 * <p>
 * Actions performed at this step:
 * <ul>
 * <li>Receives all opened browser windows
 * <li>Identifies current window and closes it
 * <li>Switches back to the window from which rederection to current window was performed
 * </ul>
 * @see <a href="https://html.spec.whatwg.org/#browsing-context"><i>Browsing context (Window &amp; Document)</i></a>
 * @see <a href="https://www.w3schools.com/tags/default.asp"><i>HTML Element Reference</i></a>
 */
@When("I close the current window")
public void closeCurrentWindow()
{
    WebDriver driver = getWebDriver();
    String currentWindow = driver.getWindowHandle();
    for (String window : driver.getWindowHandles())
    {
        if (!window.equals(currentWindow))
        {
            driver.close();
            driver.switchTo().window(window);
            break;
        }
    }
    highlightingSoftAssert.assertThat("Current window has been closed",
            String.format("Current window '%s' has been closed", currentWindow), driver.getWindowHandles(),
            not(contains(currentWindow)));
}
 
Example 2
Source File: EncapsulateOperation.java    From LuckyFrameClient with GNU Affero General Public License v3.0 6 votes vote down vote up
private static String windowHandleByTitle(WebDriver driver, String title) {
    String result = "";
    String original = driver.getWindowHandle();
    if (title.isEmpty()) {
        result = original;
    } else {
        Set<String> windowHandles = driver.getWindowHandles();
        for (String windowHandle : windowHandles) {
            driver.switchTo().window(windowHandle);
            if (title.equals(driver.getTitle())) {
                result = windowHandle;
                break;
            }
        }
        if (0 < windowHandles.size()){
        	driver.switchTo().window(original);
        } 
    }
    result = result.isEmpty() ? "��ȡ���ھ��ֵʧ�ܣ���Ҫ��ȡ���ھ��ֵ�ı��⡾" + title + "��û���ҵ�" : "��ȡ����ֵ�ǡ�" + result + "��";
    return result;
}
 
Example 3
Source File: WaitForPopup.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Override
protected Void handleSeleneseCommand(WebDriver driver, String windowID, String timeout) {
  sleepUntil.run();

  final long millis = toLong(timeout);
  final String current = driver.getWindowHandle();

  new Wait() {
    @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;
}
 
Example 4
Source File: Windows.java    From selenium with Apache License 2.0 6 votes vote down vote up
/**
 * Selects the only <code>_blank</code> window. A window open with <code>target='_blank'</code>
 * will have a <code>window.name = null</code>.
 * <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>
 * 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.
 *
 * @param driver WebDriver
 * @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<>(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");
}
 
Example 5
Source File: DesktopVideoRecorder.java    From carina with Apache License 2.0 6 votes vote down vote up
/**
 * Try to set actual browser from getDriver() on top and focused.
 * Not stable. Often browser do not switch on top and video record everything from desktop. :(
 *
 * @return boolean.
 */
private boolean setBrowserWindowOnTop(WebDriver using_driver) {
    boolean res = false;
    try {
        using_driver.manage().window().maximize();
        String windowHandle = using_driver.getWindowHandle();
        using_driver.switchTo().window(windowHandle);
        JavascriptExecutor js = (JavascriptExecutor) using_driver;
        js.executeScript("window.focus();");
        res = true;
    } catch (Exception e) {
        LOGGER.error("Exception during set focus to browser window: " + e);

    }
    return res;
}
 
Example 6
Source File: CloseTab.java    From NetDiscovery with Apache License 2.0 6 votes vote down vote up
@Override
public SeleniumAction perform(WebDriver driver) {

    String originalWindowHandle = driver.getWindowHandle();
    List<String> windowHandles = new ArrayList<String>(driver.getWindowHandles());

    if (windowHandles.size() == 1) {
        System.out.println("Skipping this step... as it possible that no new tab/window was opened");
        goBack().doIt(driver);
        return this;
    }

    windowHandles.remove(originalWindowHandle);
    for (String currentWindow : windowHandles) {
        driver.switchTo().window(currentWindow);
        driver.close();
    }

    driver.switchTo().window(originalWindowHandle);
    return this;
}
 
Example 7
Source File: EngineInvoker.java    From phoenix.webui.framework with Apache License 2.0 6 votes vote down vote up
/**
 * 关闭url以指定字符串开头的window
 * @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);
}
 
Example 8
Source File: TeasyExpectedConditions.java    From teasy with MIT License 6 votes vote down vote up
public static ExpectedCondition<String> appearingOfWindowByPartialUrl(final String url) {
    return new ExpectedCondition<String>() {
        @Override
        public String apply(final WebDriver driver) {
            final String initialHandle = driver.getWindowHandle();
            for (final String handle : driver.getWindowHandles()) {
                if (needToSwitch(initialHandle, handle)) {
                    driver.switchTo().window(handle);
                    if (driver.getCurrentUrl().contains(url)) {
                        return handle;
                    }
                }
            }
            driver.switchTo().window(initialHandle);
            return null;
        }

        @Override
        public String toString() {
            return String.format("appearing of window by partial url %s and switch to it", url);
        }
    };
}
 
Example 9
Source File: TeasyExpectedConditions.java    From teasy with MIT License 6 votes vote down vote up
/**
 * We don't know the actual window title without switching to one.
 * This method was always used to make sure that the window appeared. After it we switched to appeared window.
 * Switching between windows is rather time consuming operation
 * <p>
 * To avoid the double switching to the window we are switching to window in this method
 * <p>
 * The same approach is applies to all ExpectedConditions for windows
 *
 * @param title - title of window
 * @return - handle of expected window
 */
public static ExpectedCondition<String> appearingOfWindowAndSwitchToIt(final String title) {
    return new ExpectedCondition<String>() {
        @Override
        public String apply(final WebDriver driver) {
            final String initialHandle = driver.getWindowHandle();
            for (final String handle : driver.getWindowHandles()) {
                if (needToSwitch(initialHandle, handle)) {
                    driver.switchTo().window(handle);
                    if (driver.getTitle().equals(title)) {
                        return handle;
                    }
                }
            }
            driver.switchTo().window(initialHandle);
            return null;
        }

        @Override
        public String toString() {
            return String.format("appearing of window by title %s and switch to it", title);
        }
    };
}
 
Example 10
Source File: EncapsulateOperation.java    From LuckyFrameClient with GNU Affero General Public License v3.0 6 votes vote down vote up
private static String windowHandleByIndex(WebDriver driver, int index) {
    String result;
    try {
        List<String> windowHandles = new ArrayList<>(driver.getWindowHandles());
        if (index > windowHandles.size()) {
            result = "��ȡ���ھ��ֵʧ�ܣ���Ҫ��ȡ���ھ��ֵ���±꡾" + index + "�����ڵ�ǰ���ھ��������" + windowHandles.size() + "��";
        } else {
            if (0 >= index){
            	result = "��ȡ����ֵ�ǡ�" + driver.getWindowHandle() + "��";
            } else{
            	result = "��ȡ����ֵ�ǡ�" + windowHandles.get(index - 1) + "��";
            } 
        }
    } catch (IndexOutOfBoundsException e) {
    	LogUtil.APP.error("��ȡ���ھ��ֵ�����쳣����Ҫ��ȡ���ھ��ֵ���±꡾{}��Խ��",index,e);
        result = "��ȡ���ھ��ֵʧ�ܣ���Ҫ��ȡ���ھ��ֵ���±꡾" + index + "��Խ��";
    }
    return result;
}
 
Example 11
Source File: TeasyExpectedConditions.java    From teasy with MIT License 5 votes vote down vote up
public static ExpectedCondition<String> appearingOfWindowByUrl(final String url) {
    return new ExpectedCondition<String>() {
        @Override
        public String apply(final WebDriver driver) {
            final String initialHandle = driver.getWindowHandle();
            for (final String handle : driver.getWindowHandles()) {
                if (needToSwitch(initialHandle, handle)) {
                    driver.switchTo().window(handle);
                    try {
                        if (url.equals(URLDecoder.decode(driver.getCurrentUrl(), "UTF-8"))) {
                            return handle;
                        }
                    } catch (UnsupportedEncodingException e) {
                        LOGGER.error("UnsupportedEncodingException occured while decoding url - " + driver
                                .getCurrentUrl());
                    }
                }
            }
            driver.switchTo().window(initialHandle);
            return null;
        }

        @Override
        public String toString() {
            return String.format("appearing of window by url %s and switch to it", url);
        }
    };
}
 
Example 12
Source File: AbstractHtmlEngine.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
public AbstractHtmlEngine( UiDriver uiDriver,
                           AbstractElementsFactory elementsFactory ) {

    super(uiDriver, elementsFactory);

    AbstractHtmlDriver htmlDriver = (AbstractHtmlDriver) uiDriver;
    webDriver = (WebDriver) htmlDriver.getInternalObject(InternalObjectsEnum.WebDriver.name());
    mainWindowHandle = webDriver.getWindowHandle();
}
 
Example 13
Source File: PtlWebDriverCloserTest.java    From hifive-pitalium with Apache License 2.0 5 votes vote down vote up
@Test
public void globalTest() throws Exception {
	JUnitCore.runClasses(GlobalTestCase.class);

	for (WebDriver driver : drivers.values()) {
		driver.getWindowHandle();
	}
}
 
Example 14
Source File: PtlWebDriverCloserTest.java    From hifive-pitalium with Apache License 2.0 5 votes vote down vote up
@Test
public void testClassTest() throws Exception {
	JUnitCore.runClasses(TestClassTestCase.class);

	for (WebDriver driver : drivers.values()) {
		try {
			driver.getWindowHandle();
			fail();
		} catch (WebDriverException e) {
			assertTrue(true);
		}
	}
}
 
Example 15
Source File: DriverHelper.java    From carina with Apache License 2.0 5 votes vote down vote up
public void switchWindow() throws NoSuchWindowException {
    WebDriver drv = getDriver();
    Set<String> handles = drv.getWindowHandles();
    String current = drv.getWindowHandle();
    if (handles.size() > 1) {
        handles.remove(current);
    }
    String newTab = handles.iterator().next();
    drv.switchTo().window(newTab);
}
 
Example 16
Source File: GetAllWindowNames.java    From selenium with Apache License 2.0 5 votes vote down vote up
@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());
  }

  driver.switchTo().window(current);

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

}
 
Example 17
Source File: EncapsulateOperation.java    From LuckyFrameClient with GNU Affero General Public License v3.0 5 votes vote down vote up
private static WebDriver windowByTitle(WebDriver driver, String title) {
    String original = driver.getWindowHandle();
    Set<String> windowHandles = driver.getWindowHandles();
    for (String windowHandle : windowHandles) {
        driver.switchTo().window(windowHandle);
        if (title.equals(driver.getTitle())) {
            return driver;
        }
    }
    if (0 < windowHandles.size()){
    	driver.switchTo().window(original);
    } 
    throw new NoSuchWindowException("Window with title[" + title + "] not found");
}
 
Example 18
Source File: Windows.java    From selenium with Apache License 2.0 5 votes vote down vote up
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;
    }
  }

  driver.switchTo()
      .window(current);
  throw new SeleniumException("Unable to select window with title: " + title);
}
 
Example 19
Source File: Windows.java    From selenium with Apache License 2.0 4 votes vote down vote up
public Windows(WebDriver driver) {
  originalWindowHandle = driver.getWindowHandle();
}
 
Example 20
Source File: HTMLAnchorElement2Test.java    From htmlunit with Apache License 2.0 4 votes vote down vote up
private void javascriptTarget(final String target, final int newWindows,
                final String frameAlerts, final String windowAlerts) throws Exception {
    assertTrue(newWindows < 2);

    // real browsers (selenium) are getting confused by this scenario
    // and as result the stuck in the code that tries to get the body
    if (newWindows > 0 && useRealBrowser()) {
        assertEquals(frameAlerts, "Please run manually");
        return;
    }

    final String html
        = "<html>\n"
        + "<head><title>main</title></head>\n"
        + "<body title='main'>\n"
        + "  <iframe id='testFrame' src='" + URL_SECOND + "'></iframe>\n"
        + "</body></html>";

    final String secondHtml
        = "<html>\n"
        + "<head><title>inner</title></head>\n"
        + "<body title='inner'>\n"
        + "  <a id='tester' " + target
            + " href='javascript: try { document.body.setAttribute(\"title\", \"# \" + document.title); } "
            + "catch(e) { alert(e); }'>no href</a>\n"
        + "</body>\n"
        + "</html>";

    getMockWebConnection().setResponse(URL_SECOND, secondHtml);

    final WebDriver driver = loadPage2(html);

    final String firstWindow = driver.getWindowHandle();

    driver.switchTo().frame("testFrame");
    assertEquals(1, driver.getWindowHandles().size());
    driver.findElement(By.id("tester")).click();

    String titleVal = driver.findElement(By.tagName("body")).getAttribute("title");
    assertEquals(frameAlerts, titleVal);

    // we have to switch back to the outer content
    // otherwise selenium gets confused
    driver.switchTo().defaultContent();

    final Set<String> windows = driver.getWindowHandles();
    assertEquals(1 + newWindows, windows.size());

    if (newWindows > 0) {
        windows.remove(firstWindow);
        driver.switchTo().window(windows.iterator().next());
    }

    titleVal = driver.findElement(By.tagName("body")).getAttribute("title");
    assertEquals(windowAlerts, titleVal);
}