简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM