Selenium Java打开新窗口,关闭它,再次控制主窗口

时间:2013-11-19 18:00:25

标签: java selenium webdriver

我发现我的问题与我搜索的所有内容不同,因为我需要在代码中打开一个新窗口(而不是点击UI中的链接)。所以我已经有一个驱动程序处理我唯一的窗口,然后我这样做:

//save the handle of the current (only) window open right now
String MainWindowHandle = driver.getWindowHandle();
//open a new firefox window
driver = new FirefoxDriver();
//in the new window, go to the intended page
driver.navigate().to(foo);
//do some stuff in the pop up window..
//close the popup window now
driver.close();
//switch back to the main window. This is where the error is thrown
driver.switchTo().window(MainWindowHandle);

错误是:“org.openqa.selenium.remote.UnreachableBrowserException:与远程浏览器通信时出错。它可能已经死亡”

重新获得初始窗口的控制权需要做什么?

提前致谢。

1 个答案:

答案 0 :(得分:3)

你没有。如果你需要启动一个新的浏览器实例(听起来就像这样),那就去做吧。

// "url" is an unused variable, simply included here to demonstrate
// that the driver variable is valid and capable of being used.
String url = driver.getCurrentUrl();

// Open a new Firefox window
// Note that here, in your original code, you've set the 
// driver variable to another instance of Firefox, which
// means you've orphaned the original browser.
WebDriver driver2 = new FirefoxDriver();

// In the new window, go to the intended page
driver2.navigate().to(foo);

// Do some stuff in the pop up window..

// Close the popup window now
driver2.quit();

// No need to switch back to the main window; driver is still valid.
// Remember that "url" is simply a dummy variable used here to
// demonstrate that the initial driver is still valid.
url = driver.getCurrentUrl();