Read more

Selenium: How to close another tab (popup)

Arne Hartherz
February 27, 2013Software engineer at makandra GmbH

If you open a pop-up window [1] in your Selenium tests and you want to close it, you can do this:

# Find our target window
handle = page.driver.find_window("My window title")

# Close it
page.driver.browser.switch_to.window(handle)
page.driver.browser.close

# Have the Selenium driver point to another window
last_handle = page.driver.browser.window_handles.last
page.driver.browser.switch_to.window(last_handle)
Illustration money motivation

Opscomplete powered by makandra brand

Save money by migrating from AWS to our fully managed hosting in Germany.

  • Trusted by over 100 customers
  • Ready to use with Ruby, Node.js, PHP
  • Proactive management by operations experts
Read more Show archive.org snapshot

Mind these:

  • find_window returns a window handle, which is something like "{485fa8bd-fa99-4c26-9edc-97fed060036f}". If you already know your window's handle, you can skip that step.
  • The last section (switching to another window) is important as any subsequent steps will break when you are not pointing to a correct window.

[1] as in: a real browser window, maybe via window.open in JavaScript

Posted by Arne Hartherz to makandra dev (2013-02-27 14:24)