Get the tab the user is viewing in selenium

954 Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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.

5
On

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)