How to switch over window in Selenium Webdriver

asked 3 months ago

Switch to the window: Selenium WebDriver can also handle multiple browser windows. When a new window is opened from the current session (for example, by clicking a link), the driver must switch its context to the newly opened window in order to interact with it.

     getWindowHandle() - Returns the handle of the current window.
     getWindowHandles() - Returns a set of all open window handles.
     driver.switchTo().window(handle) - Switches WebDriver's focus to a different window using the window handle.

Example: Switching to a New Window and Back:

Navigate to https://www.qafeast.com/demo, and click the window tab.

Click the hyperlink "Click here" to view the new window

// Store the current window handle
String parentHandle = driver.getWindowHandle(); 

// Get all window handles
for (String winHandle : driver.getWindowHandles()) {
    driver.switchTo().window(winHandle); // Switch to new window
}

// Perform actions in the new window
System.out.println("New Window URL: " + driver.getCurrentUrl());

// Close the new window
driver.close();

// Switch back to the parent window
driver.switchTo().window(parentHandle);
System.out.println("Back to Parent Window URL: " + driver.getCurrentUrl());

 

Close the newly opened window when done

driver.close(); //

 

Switch back to the original window 

driver.switchTo().window(parentHandle); // switch back to the original window

 

Using Selenium Csharp

 

using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace ConsoleApp1
{
    internal class SeleniumTest
    {
        static IWebDriver driver;
        static void Main(string[] args)
        {
           
            driver = new ChromeDriver(@"\\Driver\\chromedriver.exe");
            //Implicit Wait:
            driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
            driver.Navigate().GoToUrl("https://qafeast.com/demo");
            driver.FindElement(By.XPath("//label[text()='Hyperlink']")).Click();
            string parentHandle= driver.CurrentWindowHandle;
            driver.FindElement(By.XPath("//a[text()='Web browser automation']")).Click();
            foreach (string winHandle in driver.WindowHandles)
            {
                // switch focus of WebDriver to the next found window handle (that's your newly opened window)
                driver.SwitchTo().Window(winHandle);
                // Print the new window url                                   
                Console.WriteLine(driver.Url);
            }
            // Close the current window that is newly opened window in focus.
            driver.Close();
            // Switch to Parent window / switch back to the original window 
            driver.SwitchTo().Window(parentHandle);
            // print the parent window url
            Console.WriteLine(driver.Url);
            driver.Quit();  
        }
    }
}