0

I need to open two different urls in two different tabs and then I need to keep switching between them as the flow of my application is as such.

I have included some code for opening different urls along with window handling code but it doesn't seem to be working fine as first tab would open gmail.com and then yahoo.com and second tab then opens up yahoo.com. I need to have tab1 as gmail.com and tab2 as yahoo.com and also I need to keep on switching to them anytime I want to in between the script.

    driver=new ChromeDriver();          
        driver.manage().window().maximize();
        driver.get("https://www.gmail.com");
        Thread.sleep(3000);
((JavascriptExecutor)driver).executeScript("window.open()");
        handlewindlow("Untitled"); //Untitled is title for new tab


}

        static void handlewindlow(String title) {
            Set<String>setHandleValues=driver.getWindowHandles();

Iterator<String> iteHandleValues=setHandleValues.iterator();    
                   while(iteHandleValues.hasNext()==true){
            String handleValue=iteHandleValues.next();
                driver.switchTo().window(handleValue);
                CurrentUrl=driver.getCurrentUrl();      
                String CurrentUrl=driver.getTitle();        
                driver.get("https://www.yahoo.com");

        }
    }
Adam Grunt
  • 207
  • 1
  • 3
  • 16

1 Answers1

1

Here is the logic that I would use.

WebDriver driver = new ChromeDriver();
driver.get("https://google.com");
String firstTab = driver.getWindowHandle();
// open yahoo in new tab        
JavascriptExecutor js = (JavascriptExecutor) driver; 
js.executeScript("window.open('https://yahoo.com')");
// get the 2nd browser handle
for(String winHandle : driver.getWindowHandles()){
    driver.switchTo().window(winHandle);
}
String secondTab = driver.getWindowHandle();

// switching to first tab
driver.switchTo().window(firstTab);

//switching to second tab
driver.switchTo().window(secondTab);
supputuri
  • 13,644
  • 2
  • 21
  • 39