问题
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