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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20078652/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 22:56:52  来源:igfitidea点击:

Selenium Java open new window, close it, and control main window again

javaseleniumwebdriver

提问by user1599401

I find my question to be different than everything that I've searched for because I need to open a new window in my code (not from clicking a link in a UI). So i already have a driver handling my only window, and then I do this:

我发现我的问题与我搜索过的所有问题都不同,因为我需要在我的代码中打开一个新窗口(而不是通过单击 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);

The error is: "org.openqa.selenium.remote.UnreachableBrowserException: Error communicating with the remote browser. It may have died"

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

What do I need to do to regain control of the initial window?

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

Thanks in advance.

提前致谢。

采纳答案by JimEvans

You don't. If you need to launch a new instance of the browser (which is what this sounds like), then do that.

你没有。如果您需要启动浏览器的新实例(这听起来像),请执行此操作。

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