Handle Multiple Browser Tabs using Selenium WebDriver
Program to handle two browser tabs:
public class SwitchBetweenBrowserTab { public static void main(String[] a) throws InterruptedException { // Initialize driver WebDriver driver = new FirefoxDriver(); //Maximize browser window driver.manage().window().maximize(); //Go to URL driver.get("http://www.google.com"); //Set timeout driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // Open new tab driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t"); //Go to URL driver.get("http://www.gmail.com"); //Set new tab timeout driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // Do some operation 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 first tab driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "\t"); driver.switchTo().defaultContent(); Thread.sleep(2000); // Write search String driver.findElement(By.id("gbqfq")).sendKeys("WebDriver"); // Click on Search button driver.findElement(By.id("gbqfb")).click(); Thread.sleep(2000); // Browser close driver.close(); } }
Program Explanation:
- Open Google.com
- Then open a new tab by making use of Key class. By combination of CTRL + t key a new browser tab will be opened.
- Open Gmail.com in that tab.
- Perform some actions on gmail sign in page.
- Switch back to google.com tab by pressing Ctrl + \t
- Now enter some keywords in google search box
- Close the browsers.
Follow Us
Feel free to ask queries or share your thoughts in comments or email us.
Hi,
ReplyDeleteRunning above file(SwitchBetweenBrowserTab.java),noticed that New Tab is not opening,instead New Window is opening and all the operations are done in the Same Tab of the opened Window, Please update the same
I am getting the same issue
Deletei am getting same issue and also perform on gmail then chrome tab is not getting for perform any action
Delete