vishal gupta
vishal gupta

Reputation: 55

handling 4 windows at a time in selenium

I want to switch between multiple windows and perform actions on each window. window types are like parent window>>child window>>grand child window>>grand grand child window. I have a universal code for handling multiple windows but I am not able to understand how will I call that function. I need help with that.

Can you please explain how should i call this below function and what will be the parameters in firstWindow and secondWindow?

Below is the code.

//To Handle Multiple Windows or Switch Between Multiple Windows.
    public void switchWindow(WebDriver driver, String firstWindow, String secondWindow) 
    {
        Set<String> windowHandles = driver.getWindowHandles();
        for(String windows : windowHandles) 
        {
            if(!windows.equals(firstWindow) && !windows.equals(secondWindow)) 
            {
                driver.switchTo().window(windows);
            }
        }
    }

Upvotes: 1

Views: 549

Answers (1)

Norayr Sargsyan
Norayr Sargsyan

Reputation: 1868

This methods I guess can help you to switch between windows

    public void switchToNextTab() {
        ArrayList<String> tab = new ArrayList<>(driver.getWindowHandles());
        driver.switchTo().window(tab.get(1));
    }
    
    public void closeAndSwitchToNextTab() {
        driver.close();
        ArrayList<String> tab = new ArrayList<>(driver.getWindowHandles());
        driver.switchTo().window(tab.get(1));
    }

    public void switchToPreviousTab() {
        ArrayList<String> tab = new ArrayList<>(driver.getWindowHandles());
        driver.switchTo().window(tab.get(0));
    }

    public void closeTabAndReturn() {
        driver.close();
        ArrayList<String> tab = new ArrayList<>(driver.getWindowHandles());
        driver.switchTo().window(tab.get(0));
    }

    public void switchToPreviousTabAndClose() {
        ArrayList<String> tab = new ArrayList<>(driver.getWindowHandles());
        driver.switchTo().window(tab.get(1));
        driver.close();
    }

For example, if you have 4 windows opened, and you need to switch to the next window and perform some action your code should look like this:

//first window    perform actions...
                  switchToNextTab();
//second window   perform actions...
                  closeAndSwitchToNextTab();
//third window    perform actions...
                  closeAndSwitchToNextTab();
//fourth window   perform actions...

Upvotes: 1

Related Questions