Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 318
Tree55Topz Avatar asked Jan 28 '16 16:01

Tree55Topz


People also ask

Why click is not working in Selenium?

We can list the most common reasons for click problems as being one of the following: Wrong web element locations. The existence of a web element that obscures the web element that we want to click. The Selenium WebDriver works much faster than the response of the application.

How do I click on a specific link in Selenium?

New Selenium IDE A hyperlink on a page is identified with the anchor tag. To click a link, we can use the link text locator which matches the text enclosed within the anchor tag. We can also use the partial link text locator which matches the text enclosed within the anchor tag partially.

How do you open a link of a page in a new tab in Selenium?

CONTROL+”t”); You can probably already tell that we're focusing on our webpage, then sending ctrl + t to open a new tab the way you might normally in your browser. Any time you switch between tabs, you'll want to use the driver. switchTo().


1 Answers

//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       
}
like image 140
Prageeth Saravanan Avatar answered Oct 19 '22 14:10

Prageeth Saravanan