How to Close a Pop-Up Window in Selenium WebDriver: Step-by-Step Guide

Learn how to close pop-up windows in Selenium WebDriver by switching window handles and closing pop-ups without affecting the main browser.

217 views

To close a pop-up window in Selenium, first switch to the pop-up window using `driver.switchTo().window(windowHandle)`. The `windowHandle` can be obtained from `driver.getWindowHandles()`. After switching, close the pop-up by executing `driver.close()`. Finally, switch back to the original window, if necessary, using the same `switchTo().window()` method. This approach ensures that you can close the pop-up without affecting the main browser window.

FAQs & Answers

  1. How do I switch between windows in Selenium? You can switch between windows in Selenium using driver.switchTo().window(windowHandle), where windowHandle is obtained from driver.getWindowHandles().
  2. What is the difference between driver.close() and driver.quit() in Selenium? driver.close() closes the current browser window, while driver.quit() closes all browser windows and ends the WebDriver session.
  3. How can I handle pop-up alerts in Selenium? You can handle pop-up alerts in Selenium by switching to the alert using driver.switchTo().alert() and then accept(), dismiss(), or get text as needed.