WebDriver open new tab

ChrisOdney picture ChrisOdney · Jun 21, 2011 · Viewed 50.4k times · Source

I have trawled the web and the WebDriver API. I don't see a way to open new tabs using WebDriver/Selenium2.0 .

Can someone please confirm if I am right?

Thanks, Chris. P.S: The current alternative I see is to either load different urls in the same window or open new windows.

Answer

Jonathan Azoff picture Jonathan Azoff · Feb 3, 2012

There is totally a cross-browser way to do this using webdriver, those who say you can not are just too lazy. First, you need to use WebDriver to inject and anchor tag into the page that opens the tab you want. Here's how I do it (note: driver is a WebDriver instance):

/**
 * Executes a script on an element
 * @note Really should only be used when the web driver is sucking at exposing
 * functionality natively
 * @param script The script to execute
 * @param element The target of the script, referenced as arguments[0]
 */
public void trigger(String script, WebElement element) {
    ((JavascriptExecutor)driver).executeScript(script, element);
}

/** Executes a script
 * @note Really should only be used when the web driver is sucking at exposing
 * functionality natively
 * @param script The script to execute
 */
public Object trigger(String script) {
    return ((JavascriptExecutor)driver).executeScript(script);
}

/**
 * Opens a new tab for the given URL
 * @param url The URL to 
 * @throws JavaScriptException If unable to open tab
 */
public void openTab(String url) {
    String script = "var d=document,a=d.createElement('a');a.target='_blank';a.href='%s';a.innerHTML='.';d.body.appendChild(a);return a";
    Object element = trigger(String.format(script, url));
    if (element instanceof WebElement) {
        WebElement anchor = (WebElement) element; anchor.click();
        trigger("var a=arguments[0];a.parentNode.removeChild(a);", anchor);
    } else {
        throw new JavaScriptException(element, "Unable to open tab", 1);
    }       
}

Next, you need to tell webdriver to switch its current window handle to the new tab. Here's how I do that:

/**
 * Switches to the non-current window
 */
public void switchWindow() throws NoSuchWindowException, NoSuchWindowException {
    Set<String> handles = driver.getWindowHandles();
    String current = driver.getWindowHandle();
    handles.remove(current);
    String newTab = handles.iterator().next();
    locator.window(newTab);
}

After this is done, you may then interact with elements in the new page context using the same WebDriver instance. Once you are done with that tab, you can always return back to the default window context by using a similar mechanism to the switchWindow function above. I'll leave that as an exercise for you to figure out.