Bird
0
0

How can you handle multiple tabs in Selenium Java to close all except the original tab after opening several new tabs?

hard📝 Application Q9 of 15
Selenium Java - Handling Windows, Frames, and Alerts
How can you handle multiple tabs in Selenium Java to close all except the original tab after opening several new tabs?
AStore original handle, iterate all handles, switch and close if not original
BCall driver.close() repeatedly without switching windows
CUse driver.quit() to close all tabs except original
DUse driver.switchTo().newWindow(WindowType.WINDOW) to close tabs
Step-by-Step Solution
Solution:
  1. Step 1: Save original window handle

    Keep the original tab's handle to identify it later.
  2. Step 2: Iterate over all window handles

    Loop through all open tabs/windows using driver.getWindowHandles().
  3. Step 3: Switch to each and close if not original

    Switch focus to each handle and close it if it is not the original.
  4. Final Answer:

    Store original handle, iterate all handles, switch and close if not original -> Option A
  5. Quick Check:

    Close all but original = Store original handle, iterate all handles, switch and close if not original [OK]
Quick Trick: Use getWindowHandles() and close non-original tabs [OK]
Common Mistakes:
  • Closing tabs without switching focus
  • Using driver.quit() which closes entire browser
  • Misusing newWindow() to close tabs

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Selenium Java Quizzes