如何从主窗口切换到弹出窗口? [英] How to switch from main window to popup window?

查看:193
本文介绍了如何从主窗口切换到弹出窗口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不是在谈论像警报,确认或提示对话框这样的弹出窗口。在应用程序中,如果我点击一个按钮,弹出窗口就会被打开。我无法将WebDriver切换到弹出窗口。

I'm not talking about the popups like alert, confirm or prompt dialogs. In the application if I click on a button popup gets opened. I am not able to switch the WebDriver to the popup window.


我尝试使用getWindowHandles()但它只返回主窗把手。

I've tried to use getWindowHandles() but it only returns the main window handle.

我也尝试过switchTo.window(windowname),但它没有用。

I also tried switchTo.window("windowname") but it didn't work.


推荐答案

//handle of the master window before clicking the link
String master = driver.getWindowHandle();

driver.findElement(By.linkText("Click me")).click();

//logic for waiting for the popup, checking the size to become greater than 1 or breaking after sometime to avoid the infinite loop.
int timeCount = 1;

do
{
   driver.getWindowHandles();
   Thread.sleep(200);
   timeCount++;
   if ( timeCount > 50 ) 
   {
       break;
   }
}
while ( driver.getWindowHandles().size == 1 );

//Assigning the handles to a set
Set<String> handles = driver.getWindowHandles();
//Switching to the popup window.
for ( String handle : handles )
{
    if(!handle.equals(master))
    {
         driver.switchTo().window(handle);
    }
}

这篇关于如何从主窗口切换到弹出窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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