Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to verify whether new tab opened or not in selenium webdriver?

Tags:

selenium

I have a situation where I have to check whether after clicking on a link a new tab is opened or not. If the tab opens I want to check the title as well.

Does anyone have any idea about this.

like image 535
OPTIMUS Avatar asked Apr 22 '14 11:04

OPTIMUS


People also ask

How does Selenium handle open a new window?

Open a New Tab await driver. get('https://selenium.dev'); // A new tab is opened and switches to it await driver. switchTo(). newWindow('tab'); // Loads Sauce Labs open source website in the newly opened window await driver.

Which method can be used to close a new tab opened by Webdriver in Selenium?

close() and driver. quit() are two methods for closing a browser session in Selenium WebDriver. It is necessary to know when to use each method in a test script.


2 Answers

Here is the same for C#; this is tested and will work whether the link opens in new tab or new window.

var browserTabs = driver.WindowHandles;            
driver.SwitchTo().Window(browserTabs[1]);

//check is it correct page opened or not (e.g. check page's title or url, etc.)
// ...
//close tab and get back
driver.Close();
driver.SwitchTo().Window(browserTabs[0]);

Hope this helps anyone who comes across this thread.

like image 60
amoyer Avatar answered Sep 20 '22 12:09

amoyer


You can use below method to implement the desired wait until the tab is fully loaded.

  public static void switchTabs(WebDriver driver, int expectedWindowsCount,int SwitchtoWindow) throws Exception {
    (new WebDriverWait(driver, 30)).until(ExpectedConditions.numberOfWindowsToBe(expectedWindowsCount));
    ArrayList<String> tabs2 = new ArrayList<String>(driver.getWindowHandles());
    driver.switchTo().window(tabs2.get(SwitchtoWindow));
}

The method will check how many Active window handlers are available and wait until desired handlers are present and switch to the tab afterwards.

like image 37
Avishka Perera Avatar answered Sep 17 '22 12:09

Avishka Perera