Home > Blockchain >  Selenium: close specific tab (handle) by index without switching to it
Selenium: close specific tab (handle) by index without switching to it

Time:06-18

Is it possible to close a specific tab in Selenium by index wihout switching to it?

Currently I am doing this:

driver.switch_to.window(driver.window_handles[1])
driver.close()
driver.switch_to.window(driver.window_handles[0])

I found that switching tabs makes my script very unstable, so I would prefer to avoid it if possible.

CodePudding user response:

WebDriver can close a window/tab instance if it has the focus on that particular tab or windows.

So you can not close a tab or windows if you are focusing on a different tab or windows.

If you are facing unstable script execution while switching tabs/windows I'd say have time.sleep(2) or time.sleep(3) that should help you resolve or get rid off un-stable.

Also remember, driver.quit would close all the instances.

CodePudding user response:

Actually it is possible if using chromedriver but it requires to use Chrome Developer Tools Protocol (which is supported in Selenium 4).

More specifically you have to:

  1. Get list of targets using Target.getTargets method.
  2. Extract the targetId of the page (target) you want to close.
  3. Close the page (target) using Target.closeTarget method passing the targetId.
  • Related