Friday, 6 January 2017

How to Open New Tab with Selenium WebDriver

Selenium WebDriver  tool do not have any built In API using which we can directly use to open new tab. Normally we are using CTRL + t Keys to open new tab In Browser and cltr + tab to switch between the tabs. We will use this in our selenium test case to open another tab inside a browser and switch to tab. 

Check out the Example below in details to understand how to open a new tab, how to open particular url in the new tab, how to switch between two tabs  and how to close the tabs.




import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test; 

import java.awt.Robot;
import java.awt.event.KeyEvent;

import java.awt.AWTException; 

 

public class Tabs {

 WebDriver driver; 

 Robot rb;

  

 @BeforeTest
 public void setup() throws Exception {
  System.setProperty("webdriver.chrome.driver", "C:\\Users\\Anuja.AnujaPC\\Downloads\\chromedriver_win32\\chromedriver.exe");
  WebDriver driver=new ChromeDriver();
  driver.manage().window().maximize();
  driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
  driver.get("http://qaautomated.com");
 }
 
 @Test
 public void openTab() {
  //Open tab 2 using CTRL + t keys.
  driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");
   

 //Open URL In 2nd tab.
  driver.get("http://www.qaautomated.com/p/contact.html");
  
  //Call switchToTab() method to switch to 1st tab
  switchToTab(); 

  

  //perform required actions on tab 1.
  driver.findElement(By.xpath("//input[@id='6']")).click();
  driver.findElement(By.xpath("//input[@id='plus']"));
  driver.findElement(By.xpath("//input[@id='3']"));
  driver.findElement(By.xpath("//input[@id='equals']"));
  
  //Call switchToTab() method to switch to 2nd tab.
  switchToTab();
  
  //Call switchToTab() method to switch to 1st tab
  switchToTab();

  
 } 
 
 public void switchToTab() {
  //Switching between tabs using CTRL + tab keys.
  driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"\t");
  //Switch to current selected tab's content.
  driver.switchTo().defaultContent();  
 } 

 

@AfterTest
 public void closeTabs() throws AWTException {
  //Used Robot class to perform ALT + SPACE + 'c' keypress event.
  rb =new Robot();
  rb.keyPress(KeyEvent.VK_ALT);
  rb.keyPress(KeyEvent.VK_SPACE);
  rb.keyPress(KeyEvent.VK_C);
 } }

1 comment: