1

How do I open a new tab on chrome. I need get some data from it, get back to my previous tab and input the data. I know how to iterate through the tabs, but I am not able to open a new tab.

Selenium version : 3.5.2
Chrome version : 60

package Amazon;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

public class VerifyAmazonSignInPage {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.setProperty("webdriver.chrome.driver", "C://Selenium jars/chromedriver.exe");

        WebDriver driver = new ChromeDriver();
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        driver.get("http://www.amazon.in");
        driver.findElement(By.xpath("//span[text()='Hello. Sign in']")).click();
        driver.findElement(By.id("ap_email")).sendKeys("seleniumoar1234@gmail.com");
        driver.findElement(By.id("ap_password")).sendKeys("*****");
        driver.findElement(By.id("signInSubmit")).click();
        Actions act = new Actions(driver);
        act.keyDown(Keys.CONTROL).sendKeys("t").keyUp(Keys.CONTROL).build().perform();
        driver.get("http://www.gmail.com");


    }

}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Gaurav Thantry
  • 753
  • 13
  • 30

2 Answers2

1

Thumb rule that I use for Action class is, use it only to mimic end users mouse actions. Don't use it for other purposes.

In your case, you need to send keys to the browser, you can do that using any implementation of WebDriver Interface. So how do you like to open a new tab?

Easiest way is to send key on the body element to open new tab -

   driver.findElement(By.tagName("body")).sendKeys(Keys.CONTROL + "t");

But in some of the scenarios, this don't work, so I Prefer JavascriptExecutor, I have written post on it because it is platform agnostic solution.

  ((JavascriptExecutor) driver).executeScript("window.open('http://gmail.com/','_blank');");

Note that after opening new tab, you have to take care of switching tab, it wouldn't work automatically.

Amol Chavan
  • 3,835
  • 1
  • 21
  • 32
  • Thank you @4M01 I wondered if it could be done using the actions class, but anyways this was helpful too. – Gaurav Thantry Aug 22 '17 at 09:55
  • @GauravThantry `Action` class should also work, but it fails most of the time. This is what I have observed so far. `SendKeys` is not good practice to open a new tab, It requires the browser to be active and focus is on the browser. But Javascript work regardless of this – Amol Chavan Aug 22 '17 at 09:59
0

Action class is a selenium class which can only be used to automate webbased applications. Opening a new tab is an action performed on the webbrowser, which is a stand alone application. It can be done by using the Robot class from the java.awt package.