如何切换到单击按钮后打开的新浏览器窗口?

Vol*_*iuk 80 java selenium webdriver new-window selenium-webdriver

我有情况,当点击按钮打开带有搜索结果的新浏览器窗口时.

有没有办法连接并专注于新打开的浏览器窗口?

并使用它,然后返回到原始(第一)窗口.

Sur*_*rya 103

您可以在窗口之间切换,如下所示:

// Store the current window handle
String winHandleBefore = driver.getWindowHandle();

// Perform the click operation that opens new window

// Switch to new window opened
for(String winHandle : driver.getWindowHandles()){
    driver.switchTo().window(winHandle);
}

// Perform the actions on new window

// Close the new window, if that window no more required
driver.close();

// Switch back to original browser (first window)
driver.switchTo().window(winHandleBefore);

// Continue with original browser (first window)
Run Code Online (Sandbox Code Playgroud)

  • @Elmue对于第3个(也是最后一个)时间,对于Java来说,你的答案是错误的**,因为文档和开发人员可以使用MISLEAD人员.发表答案,你说它是C#,没问题.在GitHub for Java中提出一张问题卡,继续.只是你的答案不适用于线程中的TAGGED语言,人们可能会另有想法.如果你无法区分,那么你的理解就会缺乏. (5认同)
  • 我可以确认已接受的解决方案在Chrome中一直有效但在IE中无法使用 IE中无法识别新的窗口句柄.@Elmue不正确,因为`getWindowHandles()`返回一个Set,[一个Set不保证订购](/sf/ask/752692741/).最后一个元素并不总是最后一个窗口.我很惊讶他的评论得到了很多赞成. (3认同)
  • @Elmue顺便说一句,你说driver.close()关闭两个窗口也是错误的.它只关闭电流.driver.quit()杀死所有实例.我可以看到有人已经向你指出了这一点.你的评论充满了错误.祝你有美好的一天. (3认同)
  • @Elmue 这是一个 Java 线程。请阅读 Luke (Selenium developer) [response](https://github.com/seleniumhq/selenium-google-code-issue-archive/issues/6646#issuecomment-192154324) 关于`getWindowHandles()`。这是该方法的已知行为(而非错误),尤其是 Java Set<T>。因此,在 Java 中不保证 `switchTo().window(handles[handles.length-1])`。不能声称 AC# 解决方案是正确的。 (2认同)

Ama*_*udu 12

只是添加到内容...

返回主窗口(默认窗口).

使用 driver.switchTo().defaultContent();


Pra*_*ams 11

此脚本可帮助您从父窗口切换到子窗口并将cntrl切换回父窗口

String parentWindow = driver.getWindowHandle();
Set<String> handles =  driver.getWindowHandles();
   for(String windowHandle  : handles)
       {
       if(!windowHandle.equals(parentWindow))
          {
          driver.switchTo().window(windowHandle);
         <!--Perform your operation here for new window-->
         driver.close(); //closing child window
         driver.switchTo().window(parentWindow); //cntrl to parent window
          }
       }
Run Code Online (Sandbox Code Playgroud)