I am writing scripts to automate a hybrid application. On my app I have two windowHandles.

For example, after performing some actions when I execute below code I get "2" windows as the windowHandles value.

ReadOnlyCollection<string> windowHandles = InitialiseAppium.driver.WindowHandles;

So at the script I need to close the windowHandles[1] window and navigate back to 0th window.

I tried doing this with:


But no luck yet:


This is what i currently have:

ReadOnlyCollection<string> windowHandles = InitialiseAppium.driver.WindowHandles;


Not working.

  • You should get your two handles in a list or array, try iterating your list or array.
    – Yu Zhang
    Oct 19, 2016 at 7:13
  • tried by ..No luck
    – ChathuD
    Oct 19, 2016 at 7:23
  • can you please show us what you tried?
    – Yu Zhang
    Oct 19, 2016 at 7:27

3 Answers 3


I would suggest you follow the below approach:

  • Before performing the action you mentioned, store the default(main) window handle in a string variable, say CurrentHandle using driver.getWindowHandles()
  • After the action, use the code you mentioned to get all windows in ReadOnlyCollection windowHandles
  • Iterate windowHandles and check if CurrentHandle is not equal to windowHandles loop instance
  • If loop instance is not equal to CurrentHandle, then driver.switchTo().window(windowHandles[i]) and then do driver.close()
  • After the loop, use driver.switchTo().window(CurrentHandle)
  • WIthout checking any conditions i tried closing both 0th and 1st web views, But nothing get closed.
    – ChathuD
    Oct 21, 2016 at 9:18
  • Have you ensured you used the statement driver.switchTo().window("window-handle") before you call driver.close() ? Oct 21, 2016 at 14:50
  • Yes , i did. i mention it at the 2nd time when i edit the post
    – ChathuD
    Oct 22, 2016 at 1:53

To close a new window, you first new to set the context on this new window:

element.Click();  // opens a new window

// store the handle of the main window
String winMain = driver.WindowHandle;

// set the context on the second window and close it
foreach (String winX in driver.WindowHandles) {
  if (!winX.Equals(winMain)) {

// set the context back to the main window

Note that WindowHandles returns a collection of handles where the first handle is not guarantied to be the first window. So you should not try to get an handle by index.


You can try this to close a single window,


In case of loop, you can try something like this,

for x in range(1, 6):

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.