Is there any way to determine which tab the user is viewing, like say the active tab (in selenium) is the last one and same for the user, then the user goes back to the first one, how do I know this with selenium?
Asked
Active
Viewed 706 times
1

undetected Selenium
- 183,867
- 41
- 278
- 352

Ferus
- 1,080
- 3
- 12
- 17
-
The term your looking for is handles and to get the tab the user is viewing is driver.current_window_handle. – Arundeep Chohan Dec 19 '20 at 21:28
-
1@arundeepchohan `current_window_handle` resembles the window handle on which Selenium have the focus but **not** of the user. – undetected Selenium Dec 19 '20 at 21:36
-
I think he meant the active tab in selenium. Should have reworded it. – Arundeep Chohan Dec 19 '20 at 21:38
-
1@arundeepchohan That's not the tab the user is viewing, that is active tab of *selenium* not the user. – Ferus Dec 20 '20 at 13:15
2 Answers
1
From the information that has been gathered there seem to be no way to do this. What you can do is see if the current window is the active one using:
driver.execute_script("return document.visibilityState") === "visible"
But you cannot loop through the tabs and check this property since as soon as you change tab the tab you change to will also become the visible one.

Ferus
- 1,080
- 3
- 12
- 17
0
While switching tabs you need to change Selenium's focus from one tab to other.
You can find a relevant detailed discussions in:
Selenium may not have the focus on the tab you are currently visualizing. It's the user's discretion on which tab you want Selenium to focus.
You can always extract the current window handle on which Selenium have the focus using the current_window_handle
attribute as follows:
print(driver.current_window_handle)

undetected Selenium
- 183,867
- 41
- 278
- 352
-
1Window handles are the source of truth in selenium. I would also pay attention to `driver.current_url`, but not as tightly since pages have redirects... – Yaakov Bressler Dec 19 '20 at 22:20
-
1So there is no way to know what tab the the user is visualizing? This is the question. – Ferus Dec 20 '20 at 13:16
-
@Ferus That's not what Selenium is designed to do/perform. The usecase is just the opposite. – undetected Selenium Dec 20 '20 at 13:19
-
@DebanjanB So for this case, would browser extensions be more suitable then? – Ferus Dec 20 '20 at 13:25
-