简体   繁体   中英

Selenium - Clicking a link opens up a new tab

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!

//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       
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM