Tuesday, May 27, 2014

How to move control to new tab or how to do operation in new tab ?


import java.awt.AWTException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class NewTab {
    public static void main(String[] args) throws AWTException, InterruptedException {
      
        WebDriver driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("https://www.google.co.in/?gfe_rd=cr&ei=dGKEU8HNCqeOiAenwoDgAQ");
        Actions act = new Actions(driver);
        WebElement link = driver.findElement(By.xpath("//a[text()='Gmail']"));
        act.moveToElement(link).contextClick().sendKeys("T").perform(); //open link in new tab
        act.sendKeys(Keys.chord(Keys.CONTROL,Keys.TAB)).perform();//switch to new tab by pressing control+tab
        Thread.sleep(3000); // simply wait for 3sec to see new tab open or not
        String main = driver.getWindowHandle();
        driver.switchTo().window(main);//switch control to new tab
        //act.sendKeys(Keys.chord(Keys.CONTROL,Keys.F4)).perform(); //press control+f4 to close tab
        driver.findElement(By.xpath("//input[@name='Email']")).sendKeys("hello"); //click on a 'Show all posts' link of main tab to confirm we are in main tab
    }
}

3 comments:

  1. Hi Sanjay,

    If we do just 'Ctrl+TAB', is it not sufficient? Do we also need to do driver.switchTo().window(newTabHandle) to work on the new tab that is opened?

    Thanks,
    Sreedevi

    ReplyDelete
  2. Hello Sree,

    'ctrl+tab' will just focus on new tab , it will not throw your control in new tab. So to switch control to new tab , 1st focus new tab then switch control to new tab.

    ReplyDelete