Selenium - Clicking a link opens up a new tab

12,251
//Get Current Page 
String currentPageHandle = driver.getWindowHandle();                
linkToClick.click();        

//Add Logic to Wait till Page Load 

// Get all Open Tabs
ArrayList<String> tabHandles = new ArrayList<String>(driver.getWindowHandles());

String pageTitle = "ThePageTitleIhaveToCheckFor";
boolean myNewTabFound = false;

for(String eachHandle : tabHandles)
{
    driver.switchTo().window(eachHandle);
    // Check Your Page Title 
    if(driver.getTitle().equalsIgnoreCase(pageTitle))
    {
        // Report ur new tab is found with appropriate title 

        //Close the current tab
        driver.close(); // Note driver.quit() will close all tabs

        //Swithc focus to Old tab
        driver.switchTo().window(currentPageHandle);
        myNewTabFound = true;           
    }
}

if(myNewTabFound)
{
    // Report page not opened as expected       
}
Share:
12,251
Tree55Topz
Author by

Tree55Topz

Updated on July 24, 2022

Comments

  • Tree55Topz
    Tree55Topz almost 2 years

    I have seen many threads about how to open a link in a new tab, but what about the case when you have a link that creates a new tab and you need to verify the title? All I need to do is click the link --> verify that the new tab has the correct title --> close the tab and continue on the original tab. Thanks in advance for the help!