gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 05:34:10 24 4
gpt4 key购买 nike

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

关于java - Selenium Java 打开新窗口,关闭它,并再次控制主窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20078652/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com