有一个跨浏览器的方式来做这个使用webdriver,那些谁说你不能只是太懒。首先,您需要使用WebDriver注入并将标记定位到打开所需选项卡的页面。这是我怎么做(注意:driver是一个WebDriver实例):
/**
* 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);
}
}
接下来,您需要告诉webdriver将其当前窗口句柄切换到新选项卡。这是我怎么做:
/**
* Switches to the non-current window
*/
public void switchWindow() throws NoSuchWindowException, NoSuchWindowException {
Set handles = driver.getWindowHandles();
String current = driver.getWindowHandle();
handles.remove(current);
String newTab = handles.iterator().next();
locator.window(newTab);
}
完成后,您可以使用相同的WebDriver实例与新页面上下文中的元素进行交互。一旦你完成了这个选项卡,你可以总是返回到默认的窗口上下文使用类似于switchWindow函数的机制。我将把它作为一个练习让你弄清楚。