Creating new windows/tabs in Selenium Java - Automation Script Walkthrough
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import java.time.Duration; import java.util.ArrayList; import java.util.List; public class NewTabTest { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); try { // Step 1: Navigate to example.com driver.get("https://example.com"); // Step 2: Click link/button that opens new tab // Assuming the link has id 'newTabLink' wait.until(ExpectedConditions.elementToBeClickable(By.id("newTabLink"))).click(); // Step 3: Switch to new tab List<String> tabs = new ArrayList<>(driver.getWindowHandles()); // The new tab should be the last in the list driver.switchTo().window(tabs.get(1)); // Step 4: Verify URL of new tab wait.until(ExpectedConditions.urlToBe("https://example.com/newpage")); assert driver.getCurrentUrl().equals("https://example.com/newpage") : "New tab URL mismatch"; // Step 5: Switch back to original tab driver.switchTo().window(tabs.get(0)); // Step 6: Verify URL of original tab wait.until(ExpectedConditions.urlToBe("https://example.com")); assert driver.getCurrentUrl().equals("https://example.com") : "Original tab URL mismatch"; } finally { // Close all tabs and quit driver.quit(); } } }
This code uses Selenium WebDriver with Java to automate the test case.
We start by setting up the ChromeDriver and opening the browser to 'https://example.com'.
We wait until the element with id 'newTabLink' is clickable and click it to open a new tab.
We then get all window handles and switch to the new tab, which is the second window handle.
We wait until the URL of the new tab is 'https://example.com/newpage' and assert it matches.
Next, we switch back to the original tab and verify its URL is still 'https://example.com'.
Finally, we close all browser windows with driver.quit() to clean up.
Explicit waits ensure the page loads before assertions, and using window handles properly switches between tabs.
Now add data-driven testing with 3 different URLs that open in new tabs and verify each.