How to get currently active tab index on Chrome via Selenium?

五迷三道 提交于 2019-12-20 06:15:47

问题


I'm creating app which is half-automated (user is opening tabs (attention) and if he wants to dump one of them he just clicks hot-key).

But when user opens to much tabs, I need to know to which one I should switch. How can i get currenttab index. Or switch to current tab on Selenium C#?

string windowHandle = Browser.WindowHandles.Last();
string windowHandle = Browser.WindowHandles.First();
string windowHandle = Browser.WindowHandles[1];

... is not working for me.


回答1:


The currenttab index may get changed everytime you invoke Browser.WindowHandles().

Though the general perception is WindowHandles would be sorted like the oldest windows first and the newest windows last. But this is not the case: It is totaly random !

In a discussion, Simon clearly mentioned:

While the datatype used for storing the list of handles may be ordered by insertion, the order in which the WebDriver implementation iterates over the window handles to insert them has no requirement to be stable. The ordering is arbitrary.

This comment is pretty much inline with the Get Window Handles section where it mentioned:

In order to determine whether or not a particular interaction with the browser opens a new window, one can obtain the set of window handles before the interaction is performed and compare it with the set after the action is performed.

You can find a relevant detailed discussion in Best way to keep track and iterate through tabs and windows using WindowHandles using Selenium


Update

As per your comment user switch tab (in window) but driver is still focused on another tab you need to induce WebDriverWait for numberOfWindowsToBe(n) and you can find a detailed discussion in getWindowHandles() not working in firefox 58.The focus remains on parent tab and does not transfer to next tab



来源:https://stackoverflow.com/questions/57532534/how-to-get-currently-active-tab-index-on-chrome-via-selenium

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!