Selenium 4 – Browser New Tab
Selenium 3 does not have any feature to open a new Browser Tab though it can be done with the help of Java script executor.
Selenium 4 Alpha version has introduced a feature to open a new Browser Tab. Let’s see how it works.
Its achieved through following simple line of code
webDriver.switchTo().newWindow(WindowType.TAB);
Test case code
Following test case, opens gmail, opens a new tab and then loads yahoo.co.in url
package selenium4.selenium4;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class seleniumNewTab {
WebDriver webDriver = null;
@BeforeTest
public void beforeTest() throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\\Selenium\\Chrome84\\chromedriver.exe");
webDriver = new ChromeDriver();
webDriver.manage().window().maximize();
Thread.sleep(2000);
webDriver.get("https://www.gmail.com/");
}
@Test
public void checkNewTab() {
webDriver.switchTo().newWindow(WindowType.TAB);
webDriver.get("http://www.yahoo.co.in");
}
@AfterTest
public void afterTest() {
webDriver.quit();
}
}
Opening a new tab also be done using Javascript executor but it wont used any more.
((JavascriptExecutor) webDriver).executeScript("window.open()");
ArrayList<String> tabs = new ArrayList<String>(webDriver.getWindowHandles());
webDriver.switchTo().window(tabs.get(1));