1

I am trying to do basic browser-tab operations for Chrome browser like -

  1. opening a new tab
  2. switching to it
  3. closing the tab

However, none of the methods that I tried are working, listed below:

  1. Actions class in Selenium --- actions.click(driver.findElement(By.cssSelector("body"))).keyDown(Keys.LEFT_CONTROL).sendKeys("t") .keyUp(Keys.LEFT_CONTROL).build().perform();

  2. Through sendKeys() --- driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");

I also searched the net for a solution but all these issues are 3 to 4 years old and it appears the listed solutions are not working for me :(

I am using:

  1. Java 8
  2. Selenium v3.141.59
  3. Chrome v80.0.3987.132
  4. webdrivermanager v3.8.1

Please reply if you know any solution or workaround for this; any help will be appreciated.. :)

Thanks

nvn
  • 45
  • 1
  • 8

1 Answers1

1

On of the best ways is to find the element and press on it by .sendKeys(); in order to open in a new tab and switch to it. Just like that:

//opening in a new tab
        driver.findElement(By.id("abc")).sendKeys(Keys.chord
(Keys.CONTROL, Keys.ENTER)); 

    // adding all the tabs to set
    Set<String> tabIDs = driver.getWindowHandles(); 

// creating iterator for going through the set of your opened tabs
    Iterator<String> iterator = tabIDs.iterator(); 

// switching to the next tab
    driver.switchTo().window(iterator.next()); 

    // or you can loop it like below and iterate automatically after some actions in the each tab
    while (iterator.hasNext()) {
          driver.switchTo().window(iterator.next());
          // do something
    }
Villa_7
  • 508
  • 4
  • 14
  • Thakyou for your answer. Unfortunately, my scenario was a little bit different. However, my issue got resolved after I followed these steps :) --- https://stackoverflow.com/questions/49031048/selenium-switch-focus-to-tab-which-opened-after-clicking-link – nvn Mar 26 '20 at 08:05