Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium webdriver window handles c# switchTo failed

Here comes 2 windows pop out during the testing.

my code:

string BaseWindow = driver.CurrentWindowHandle;                 
ReadOnlyCollection<string> handles = driver.WindowHandles;

foreach(string handle in handles)                    
{                         
    Boolean a = driver.SwitchTo().Window(handle).Url.Contains("Main");
    if (a == true)  
    {       
        InitialSetting.driver.SwitchTo().Window(handle);      
        break;
    }  
}                

I want to switch to the window which url contains "Main". But when the test is running, it switches between two windows continuously and it doesn't stop.

I debug and found the foreach didn't break even when the boolean a is true.

How can I resolve this?

like image 369
user1487331 Avatar asked Jun 28 '12 02:06

user1487331


2 Answers

//switch to new window 
driver.FindElement(By.Id("link")).Click(); 

//wait for new window to open 
Thread.Sleep(2000); 

//get the current window handles 
string popupHandle = string.Empty; 
ReadOnlyCollection<string> windowHandles = driver.WindowHandles;  

foreach (string handle in windowHandles)  
{  
    if (handle != existingWindowHandle)  
    {  
         popupHandle = handle; break;  
    }  
}  

 //switch to new window 
driver.SwitchTo().Window(popupHandle); 

//check for element on new page 
webElement = driver.FindElement(By.Id("four04msg")); 
if(webElement.Text == "THE CONTENT YOU REQUESTED COULDN’T BE FOUND...")  
{  
    return false;  
}  
else  
{  
    return true;  
}  

 //close the new window to navigate to the previous one
driver.close(); 

//switch back to original window 
driver.SwitchTo().Window(existingWindowHandle);
like image 112
Michael Ayers Avatar answered Oct 11 '22 15:10

Michael Ayers


  1. Using the original post code.

    string existingWindowHandle = driver.CurrentWindowHandle;

    Its the first window.

  2. One important thing is:

    ReadOnlyCollection<string> windowHandles = driver.WindowHandles

    Contains the string name object, not the Windows Title Name, for example Collection windowHandles could contains:

    Not Windows Title Name as {Menu},{PopUp}
    It contains: {45e615b3-266f-4ae0-a508-e901f42a36d3},{c6010037-0be6-4842-8d38-7f37c2621e81}

like image 42
dmunozpa Avatar answered Oct 11 '22 16:10

dmunozpa