6

I'm trying to open a link in a new tab, then switch to that tab, in a Firefox browser, using selenium in Java. It's my understanding that in order to do this, I need to use a send keys combination.

In order to open the link in the same window, I've been using something like this:

WebElement we = driver.findElement(By.xpath("//*[@id='btn']"));

JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].click();", we);

The above was working fine for me.

Now I'm trying to also sendKeys, as in below, which is not working:

JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("keyDown(Keys.CONTROL)
                        .keyDown(Keys.SHIFT)
                        .click(arguments[0])
                        .keyUp(Keys.CONTROL)
                        .keyUp(Keys.SHIFT);", we);

Any advice? I can't figure out the correct syntax to sendKeys to JavascriptExecutor. I've seen some similar solutions using Actions, but this hasn't worked for me either.

ch-pub
  • 1,664
  • 6
  • 29
  • 52
  • When you've used Actions to perform CTRL+SHIFT+click, what happened? Thanks. – alecxe Jul 26 '15 at 02:03
  • @alecxe Actually, if I use `new Actions(driver).keyDown(Keys.CONTROL).keyDown(Keys.SHIFT).click(we).keyUp(Keys.C‌​ONTROL).keyUp(Keys.SHIFT).perform();`, then the link is opened in the *current* tab. I can't figure out how to make this work properly either. – ch-pub Jul 26 '15 at 03:36
  • Why do you want to execute sendKeys using Actions or JavascriptExecutor? Plain Selenium WebElement doesn't work? – automatictester Jul 26 '15 at 10:07

1 Answers1

1

try below code to open any link on page to new tab & switch to that tab. Perform operations there & go back to first tab for further execution.

WebDriver driver = new FirefoxDriver();
        driver.get("http://stackoverflow.com/");
        WebElement e = driver.findElement(By.xpath(".//*[@id='nav-questions']"));       
        Actions action = new Actions(driver); 
        action.keyDown(Keys.CONTROL).build().perform(); //press control key
        e.click();
        Thread.sleep(10000); // wait till your page loads in new tab
        action.keyUp(Keys.CONTROL).build().perform(); //release control key
        driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "\t"); //move to new tab
        driver.navigate().refresh(); // refresh page
        driver.findElement(By.xpath(".//*[@id='hlogo']/a")).click(); //perform any action in new tab. I am just clicking logo
        driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "\t"); //switch to first tab
        driver.navigate().refresh(); 
        driver.findElement(By.xpath(".//*[@id='hlogo']/a")).click();// refresh first tab & continue with your further work.I am just clicking logo
Deepak
  • 336
  • 1
  • 3
  • 10