2

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:

driver.close();
driver.Navigate().Back();

But no luck yet:

_+_+_+_+_+_+_+_+__+

This is what i currently have:

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

InitialiseAppium.driver.SwitchTo().Window(windowHandles[0]);
InitialiseAppium.driver.Close();

Not working.

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

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 '16 at 9:18
  • Have you ensured you used the statement driver.switchTo().window("window-handle") before you call driver.close() ? – BountyHunter Oct 21 '16 at 14:50
  • Yes , i did. i mention it at the 2nd time when i edit the post – ChathuD Oct 22 '16 at 1:53
0

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)) {
    driver.SwitchTo().Window(winX);
    driver.Close();
  }
}

// set the context back to the main window
driver.SwitchTo().Window(winMain);

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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