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

我发现我的问题与我搜索过的所有内容都不同,因为我需要在代码中打开一个新窗口(而不是单击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:与远程浏览器通信时出错。它可能已经死亡”

我需要做些什么才能重新获得对初始窗口的控制权?

提前致谢。

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

 // "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();