Monday, 17 March 2014

How to handle multiple browser windows in Selenium Webdriver in C#.Net?

We can use 2 properties to handle multiple browser windows in Selenium Webdriver.
  1. CurrentWindowHandle -
  2. WindowHandles - gets the collection of all open windows

Complete example in C#.Net to handle multiple windows is given below



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.IE;
using OpenQA.Selenium.Support.UI;
using System.Collections.ObjectModel;
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium.Interactions.Internal;
using OpenQA.Selenium.Support.UI;

namespace Abc
{
    class Program
    {
        static void Main(string[] args)
        {

           
IWebDriver driver=null;
try
{

   driver = new ChromeDriver(@"F:\selenium\csharp");
   driver.Url = "http://www.google.co.in";

   driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(20));

   driver.Navigate();

driver.FindElement(By.Id("link")).Click();
String popWindowHandle = "";
//get the current window handles
String mainWindow = driver.CurrentWindowHandle;

//get the collection of all open windows
ReadOnlyCollection<string> windowHandles = driver.WindowHandles;
foreach (string handle in windowHandles)
{
if (handle != mainWindow)
{
newWindowHandle = handle;
break;
}
}
//switch to new pop up window
// and perform any operation you want to perform
driver.SwitchTo().Window(newWindowHandle);
//Print the title of new pop up window just opened.
Console.WriteLine(driver.Title);
driver.Close();
//switch back to original window
driver.SwitchTo().Window(mainWindow);
} catch(Exception e){ Console.WriteLine("Exception ******"+e.ToString()); } finally{ Thread.Sleep(2000); driver.Quit(); Console.ReadLine(); } } } }
What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

No comments:

Post a comment

Buy Best Selenium Books