Selenium Java 打开新窗口,关闭它,再次控制主窗口 [英] Selenium Java open new window, close it, and control main window again

查看:27
本文介绍了Selenium Java 打开新窗口,关闭它,再次控制主窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

//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:与远程浏览器通信时出错.它可能已经死了"

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

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

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

提前致谢.

推荐答案

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

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

这篇关于Selenium Java 打开新窗口,关闭它,再次控制主窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆