Selenium WebDriver - Handle Multiple Browser Tabs

We can perform a number of actions by combining third party things along with Webdriver, which webdriver is not capable if doing it alone. In this context sharing with you a program of handling multiple tabs. We can make use of Key controls which Robot api of java provides, to handle multiple tabs.

Example Code:

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();  
   }  
 }  



Happy Learning!

Feel free to ask queries or share your thoughts in comments or email me. Happy Learning! :)

Blog Author: Vaneesh Behl
Join Telegram channel of this blog at https://t.me/techlisticspace

Comments

Post a Comment

Popular Posts

Top 10 Demo Websites to Practice Selenium Webdriver Online

Future of Selenium Automation Testing as a Career Option

How to learn Selenium Webdriver on your own online

Selenium WebDriver - Take Screenshot and Partial Screenshot Commands

Selenium Webdriver - Overview & Features