In Selenium Webdriver script how to open a new browser tab and then switch between first browser tab and 2nd browser tab?
Solution: This is the script to achieve it, go through comments in the code to understand how the code works:
public static void main(String[] args) throws InterruptedException
{
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
//URL of 1st Tab which is opened by default on browser launch
driver.get("http://www.google.com");
// tab timeout - let the browser load the page
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// Open 2nd tab now
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");
//load a new website in 2nd Tab
driver.get("http://www.gmail.com");
//tab timeout - let the browser load the page
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// perform some operation on 2nd tab if needed
driver.findElement(By.id("gmail-sign-in")).click();
driver.findElement(By.id("Email")).sendKeys("WebDriver");
driver.findElement(By.id("Passwd")).sendKeys("WebDriver");
driver.findElement(By.id("signIn")).click();
Thread.sleep(2000);
// Switch back to first tab
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "\t");
driver.switchTo().defaultContent();
Thread.sleep(2000);
driver.close();
}
}
