2

Some people including me were suffering from this issue called "OpenQA.Selenium.WebDriverException: [windowHandle] is not a top level window handle".

Shabbir Hossain
  • 107
  • 1
  • 11

3 Answers3

4

There are lot of question asked and answered on "how to attach to a TopLevelWindow" but literally none is talking on "how to attach to a NonTopLevelWindow". I searched a lot for a solution but there was nothing on it. But after reading a code shared in this answer on GitHub, I realized what the solution is.
I was so disgusted after it because of the simplicity of the solution! Then I thought to share it with everyone.

The solution is so simple. As the new window which is a Child Node (i.e. resides under the main application tree), we can not attach to it by creating a new session. The reason is that, it is not a top level window and we can only attach to a top level window with this process explained on GitHub.
What we need to do is just simply search for the window by its name and you will get access of that window (same as finding an UI element)

For example- This code is for such a window which is a TopLevelWindow:

# create a desktop session to find the new window
desired_caps = {}
desired_caps["app"] = "Root"
newDriver = webdriver.Remote(WindowsApplicationDriverUrl, desired_caps)

# Find the NativeWIndowHandle of the new window
newWindow = newDriver.find_element_by_name("SmarTTY - New SSH Connection")
newWindowHandle = newWindow.get_attribute("NativeWindowHandle")

# create a new session to attach the new window with its NativeWindowHandle
desired_caps = {}
desired_caps["appTopLevelWindow"] = newWindowHandle
connWinDriver = webdriver.Remote(WindowsApplicationDriverUrl, desired_caps)

And this code is for such a window which is a NonTopLevelWindow:

# Find the new window
newPopUpWindow = driverMain.find_element_by_name("SmarTTY - New SSH Connection")

In this case the first code will not work due to the window is not being a top level window. But the second code will work.
This window (window name is SmarTTY - New SSH Connection) pops open after I click a button on the previous window. The application name on which this example is based on is SmarTTY. And the above codes are Python codes for WinAppDriver.

Shabbir Hossain
  • 107
  • 1
  • 11
  • 1
    The topLevelWindow mechanism gives us a few other advantages like creating a session out of it and once a session is created it is easy to do manipulations like "newSessionByName.close()" will close the top level window. I feel like when it is not a top level window we miss out on these advantages. I am clicking on cancel, ok etc to dismiss the popup. – Monnie_tester Jun 18 '21 at 21:18
0

Here is my C# code, I am adding it as desired capabilities are depricated and options should be used instead:

    AppiumOptions rootSessionOptions = new AppiumOptions();
    rootSessionOptions.AddAdditionalCapability("app", "Root");
    rootSessionOptions.AddAdditionalCapability("deviceName", "WindowsPC");
    _driver = new WindowsDriver<WindowsElement>(new Uri("http://127.0.0.1:4723"), rootSessionOptions);
    _driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);

    var VSWindow = _driver.FindElementByName("Your project name without .csproj - Microsoft Visual Studio");
    var VSTopLevelWindowHandle = VSWindow.GetAttribute("NativeWindowHandle");
    VSTopLevelWindowHandle = (int.Parse(VSTopLevelWindowHandle)).ToString("x");

    AppiumOptions VisualStudioSessionOptions = new AppiumOptions();
    VisualStudioSessionOptions.AddAdditionalCapability("appTopLevelWindow", VSTopLevelWindowHandle);
    _driver = new WindowsDriver<WindowsElement>(new Uri("http://127.0.0.1:4723"), VisualStudioSessionOptions);

    _driver.SwitchTo().Window(_driver.WindowHandles[0]);
K. B.
  • 3,342
  • 3
  • 19
  • 32
  • This is the code for a topLevelwindow or for a "nonTopLevelWindow"? – Monnie_tester Jun 18 '21 at 21:15
  • This is for a topLevelwindow. NonTopLevelWindow can be found similar to VSWindow - after you have attached to the topLevelWindow and similar to Shabbir's second code snippet : var NonTopLevelWindow= _driver.FindElementByName("Your window name"); – K. B. Jun 19 '21 at 15:36
0
    # After login i am not able to perform any operation 
#Conftest file code 
import pytest
from appium import webdriver


@pytest.fixture(scope="class")
def setUp(request):

desired_caps = {}
desired_caps["app"] = r"C:\\Program Files (x86)\\Giesecke Devrient\\Compass VMS\\Compass VMS.exe"
driver = webdriver.Remote(command_executor='http://127.0.0.1:4723',
                          desired_capabilities= desired_caps)
#driver.implicitly_wait(10)
request.cls.driver = driver
yield
    driver.close()


#Main Code  
    from appium import webdriver
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver import ActionChains
    from selenium.webdriver.common.keys import Keys
    from selenium.webdriver.support.wait import WebDriverWait
    from Utility.Base import BaseClass
    
    
    # @pytest.mark.usefixtures("setUp")
    class TestDe_Login(BaseClass):
    
        def test_initialize(self):
            self.driver.find_element_by_xpath("//*[@Name='Login']//*[@LocalizedControlType='text' "
                                              "and @Name='User ID:']/..//*[@LocalizedControlType='edit']").send_keys("t2")
            self.driver.find_element_by_accessibility_id("passwordTextBox").send_keys("1")
            self.driver.find_element_by_name ("&Login").click()
wait = WebDriverWait(self.newDriver, 20)
    wait.until(EC.presence_of_element_located((By.NAME, '&Logout'))).click()[enter image description here][1]
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 08 '21 at 12:18
  • If you have a new question, please ask it by clicking the [Ask Question](https://stackoverflow.com/questions/ask) button. Include a link to this question if it helps provide context. - [From Review](/review/late-answers/30536180) – SiKing Dec 08 '21 at 23:26