Is there a way to close a tab in WebDriver or Protractor?

后端 未结 8 1276
悲&欢浪女
悲&欢浪女 2020-12-01 06:37

Is there a way to physically close a tab via Protractor or WebDriver?

I ask because while I know how to switch tabs programmatically, but it does not bring the acti

8条回答
  •  鱼传尺愫
    2020-12-01 06:49

    Close all tabs except first one and switch to first tab:

    var tabs = driver.WindowHandles; // 
    
    foreach (var tab in tabs)
    {
         // "tab" is a string like "CDwindow-6E793DA3E15E2AB5D6AE36A05344C68"
         if (tabs[0] != tab) 
         {                                    
             driver.SwitchTo().Window(tab); 
             driver.Close();
         }
    }
    
    driver.SwitchTab(tabs[0]); // Switch to first tab
    driver.SwitchTo().DefaultContent(); // Switch to default frame
    

    Pay attention to last two lines, they are need to avoid such errors like OpenQA.Selenium.NoSuchWindowException: no such window: target window already closed from unknown error: web view not found

提交回复
热议问题