Selenium WebDriver - Handle Multiple Browser Tabs

In this tutorial, you will learn to open and handle multiple browser tabs within a single Selenium script.  We can make use of Key controls of Actions class of Selenium Webdriver or Robot Class of java to handle multiple tabs.



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.

Refer Selenium Webdriver Tutorials Series

Subscribe FB Group Techlistic.com
Join Telegram channel at https://t.me/techlistic
Feel free to ask queries or share your thoughts in comments or email me.

Comments

Post a Comment

Popular Posts

Top 20 Advanced Selenium Webdriver Coding Interview Questions of 2019

Top 10 Demo Websites to Practice Selenium Webdriver Online

Selenium Essentials - How to become expert in Automation Testing?

Top 25 Must to know Selenium Webdriver Commands List

Selenium WebDriver - Handle Alerts or Pop-Ups