简体   繁体   中英

How to open a new tab in chrome using selenium

I am trying to open a new tab in selenium, but it not working. It opens the url in the same tab.

Code:

        cDriver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");
        cDriver.get(url1);
        cDriver.switchTo().window(tabs.get(1)); 

getting below exception:

    java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
atcom.freedomoss.crowdcontrol.webharvest.plugin.selenium.RobotPlugin.executePlugin(RobotPlugin.java:187)
at org.webharvest.runtime.processors.WebHarvestPlugin.execute(WebHarvestPlugin.java:125)
at org.webharvest.runtime.processors.BaseProcessor.run(BaseProcessor.java:127)
at org.webharvest.runtime.processors.BodyProcessor.execute(BodyProcessor.java:27)
at org.webharvest.runtime.processors.WebHarvestPlugin.executeBody(WebHarvestPlugin.java:246)
at com.freedomoss.crowdcontrol.webharvest.plugin.selenium.RoboticsFlowPlugin.executePlugin(RoboticsFlowPlugin.java:98)
... 16 more

You can open new tab with javascript

public void openNewTab() {
    ((JavascriptExecutor)driver).executeScript("window.open('about:blank','_blank');");
}

If you want to perform operations within new tab you can use:

driver.switchTo().window(); This method accepts String as an argument. Window handle to be exact

You can get all handles like this

driver.getWindowHandles() . This will return you a Set of all handles in the current browser.

In order to switch to newly created tab, iterate through the handles and use switchTo() method like this:

    Set<String> handles = driver.getWindowHandles();
    String currentWindowHandle = driver.getWindowHandle();
    for (String handle : handles) {
        if (!currentWindowHandle.equals(handle)) {
            driver.switchTo().window(handle);
        }
    }

WARNING: This might be tricky if you have more than 2 tabs.

The code will open the link in new Tab.

String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL,Keys.RETURN); 
driver.findElement(By.linkText("urlLink")).sendKeys(selectLinkOpeninNewTab);

This way will work:

driver.get("https://www.google.com.br/");

    Robot robot = new Robot();
    robot.delay(1000);
    robot.keyPress(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_T);
    robot.keyRelease(KeyEvent.VK_T);
    robot.keyRelease(KeyEvent.VK_CONTROL);
    robot.delay(2000);

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

    driver.get("https://br.yahoo.com/");

You normally need to change the driver to the tab that you want to use. If you need to close that tab, you can use driver.close(); but to use the flist tab, you will need to use another swichTo.

I'm a little late to the party here, but I feel like a lot of these solutions don't provide an easy mechanism for switching to the new tab. Here's my approach. As a bonus it will switch back to the original tab on error.

public static <W extends WebDriver & JavascriptExecutor> String newTab(W webDriver) {
    Objects.requireNonNull(webDriver);
    String currentHandle = webDriver.getWindowHandle();
    String newTabHandle = null;
    try {
        String template = "var win=window.open('about:blank','_blank');win.document.write('<html><body style=\"display:none\" class=\"%s\"></body></html>');win.document.close();";
        String className = "tab" + UUID.randomUUID().toString().replaceAll("\\W+", "");
        String script = String.format(template, className);
        webDriver.executeScript(script);
        newTabHandle = new FluentWait<>(webDriver).pollingEvery(Duration.ofMillis(100)).until(nil -> {
            Iterator<String> handleIter = webDriver.getWindowHandles().stream()
                    .filter(v -> !currentHandle.equals(v)).iterator();
            while (handleIter.hasNext()) {
                var handle = handleIter.next();
                webDriver.switchTo().window(handle);
                var elements = webDriver.findElements(By.cssSelector("." + className));
                if (!elements.isEmpty())
                    return handle;
            }
            return null;
        });
    } finally {
        if (newTabHandle == null)
            webDriver.switchTo().window(currentHandle);
    }
    if (newTabHandle == null)
        throw new IllegalStateException("new tab creation failed");
    return newTabHandle;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM