1

How to transfer control from old tab to new tab using WebDriver? Suppose I open a link in new tab and then I want to perform some actions in that newly open tab. How can I do this?

When I open a link in new tab, the control still exist in old tab. Please provide a solution.

For example: I opened the link "Create a account" in gmail to new tab and then I try to fill text fields available in form, but when I run the program, it always say that elements not found

Thanks.

Ripon Al Wasim
  • 36,924
  • 42
  • 155
  • 176
gaurav_saini
  • 11
  • 1
  • 2

2 Answers2

0
new Actions(driver).sendKeys(driver.findElement(By.tagName("html")), Keys.CONTROL).sendKeys(driver.findElement(By.tagName("html")),Keys.NUMPAD2).build().perform();

will pass the control to new tab (this script assumes new tab is second tab).

Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_W);
robot.keyRelease(KeyEvent.VK_W);
robot.keyRelease(KeyEvent.VK_CONTROL);

This will close the new tab.

new Actions(driver).sendKeys(driver.findElement(By.tagName("html")), Keys.CONTROL).sendKeys(driver.findElement(By.tagName("html")),Keys.NUMPAD1).build().perform();

Will switch back to original tab.

Related questions
Selenium 2: Open link in new tab and close tabs
switch tabs using Selenium WebDriver with Java

Community
  • 1
  • 1
Ajinkya
  • 22,324
  • 33
  • 110
  • 161
  • Hi, this is my code: public void test() throws Exception { WebDriver driver= new FirefoxDriver(); driver.get("http:/www.gmail.com"); WebElement element=driver.findElement(By.linkText("Create an account")); Actions oAction= new Actions(driver); oAction.moveToElement(element); oAction.contextClick(element).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build().perform(); Thread.sleep(10000); driver.findElement(By.id("FirstName")).sendKeys("gaurav"); driver.findElement(By.id("LastName")).sendKeys("saini"); } I opened 'Create a account' in new tab and want to fill form – gaurav_saini Mar 03 '14 at 09:48
  • But control is still in previous tab, it always says element not found, please help for this how to get over from this. – gaurav_saini Mar 03 '14 at 09:50
0
//declare selectLinkOpeninNewTab above the main method 
static String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL,Keys.RETURN);

// to open your seession in new tab
driver.findElement(By.id("")).sendKeys(selectLinkOpeninNewTab);
driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);

// to perform actions
driver.switchTo().activeElement().sendKeys(Keys.CONTROL,Keys.NUMPAD2);   

// for example thease are your actions
driver.findElement(By.id("")).click();
driver.findElement(By.id("")).clicl();

// to close new tab and back to current tab
driver.findElement(By.tagName("body")).sendKeys(Keys.CONTROL+"w");
Patrick Trentin
  • 7,126
  • 3
  • 23
  • 40
megha
  • 1
  • 1