Search code examples
seleniumselenium-webdriverselenium-gridsafari-extensionsafaridriver

Grid-Safari-Selenium is getting stuck on SafariDriver Launcher page[second Tab] by not closing it and NOT switching back to first Tab


Meta -

OS: OSX El capitan Selenium Version: 2.53.0 Browser: Safari Browser Version: 9.1 SafariDriver version: 2.48.0 which is latest as per SeleniumHQ site.

Expected Behavior -

SafariDriver Launcher page/tab should get closed automatically and get switched to first tab where my URL is getting opened.

Actual Behavior -

Selenium is getting stuck on SafariDriver Launcher page[Tab] by not closing it and switching back to first Tab

Steps to reproduce -

Trying to execute n number of test cases from TestNG.xml, but few TCs are getting executed properly by closing SafariDriver Launcher page[tab]. But for few cases Selenium is getting stuck on SafariDriver Launcher page[Tab] by not closing it and switching back to first Tab where my URL will get opened.

Required Solution -

I wanna first check how many tabs are currently opened by:-

if(browser.equals("safari")){
capability=DesiredCapabilities.safari();
capability.setBrowserName("safari");
capability.setPlatform(Platform.MAC);
capability.setVersion("9.1");
capability.setJavascriptEnabled(true);
driver=new RemoteWebDriver(new URL(grid_url),capability);
driver.get(url);
Thread.sleep(2000);
String windowHandle = driver.getWindowHandle();
ArrayList tabs = new ArrayList (driver.getWindowHandles());
if(tabs.size()>1){

        <***Need a solution here to close second tab and switch to   first tab***>
                    driver.switchTo().window(tabs.get(0));
        }
}

Solution

  • You can use this code to close the window you want to :

    for(String handle : driver.getWindowHandles()) {
            if (!handle.equals(originalHandle)) { //the window handle you want to close
                driver.switchTo().window(handle);
                driver.close(); // would close the specific tab you wanted
            }
        }
    

    In your case originalHandle could be the handle for the current window (tab 2) you are at.