This guide shows you how to switch between multiple browser windows and tabs when automating with Selenium WebDriver and PHP. You’ll learn to grab window handles, switch context, close specific windows, and manage pop-ups—essential for testing multi-step flows like payment gateways or social logins. No prior Selenium experience is needed, but basic PHP and Composer knowledge helps.
What You’ll Need
- PHP 7.4 or newer
- Composer installed
- Selenium WebDriver (the server) running locally or remotely
- php-webdriver library (install via
composer require php-webdriver/webdriver) - A browser driver (ChromeDriver, GeckoDriver, etc.) matching your browser version
Step-by-Step
- Set up the WebDriver session. Start your Selenium server and create a WebDriver instance. For Chrome, use
ChromeDriverand pass desired capabilities. Example:$host = 'http://localhost:4444'; $driver = RemoteWebDriver::create($host, DesiredCapabilities::chrome()); - Open the initial window. Use
get()to navigate to your starting URL. This creates the first window handle.$driver->get('https://example.com'); - Get the current window handle. Store the handle of the first window so you can return to it later.
$mainWindow = $driver->getWindowHandle(); - Open a new tab or window. Use JavaScript to open a new tab, or click a link that opens a pop-up. For a new tab:
$driver->executeScript("window.open('https://example.org', '_blank');"); - Get all window handles. After opening, fetch all handles with
getWindowHandles(). This returns an array.$handles = $driver->getWindowHandles(); - Switch to the new window. Loop through the handles and switch to the one that isn’t the main window. Use
switchTo()->window($handle).foreach ($handles as $handle) { if ($handle != $mainWindow) { $driver->switchTo()->window($handle); break; } } - Do something in the new window. For example, verify the title or interact with elements.
$newTitle = $driver->getTitle(); echo "New window title: $newTitle"; - Close the new window. Call
close()to close the current window (the one you are on).$driver->close(); - Switch back to the main window. After closing, you must switch back to the original handle to continue.
$driver->switchTo()->window($mainWindow); - Handle pop-ups (alerts). If a window opens as a JavaScript alert, use
switchTo()->alert()to accept or dismiss.$driver->switchTo()->alert()->accept();
Common Mistakes
- Forgetting to switch back to the main window after closing a tab—this causes ‘NoSuchWindowException’.
- Assuming the handle order is predictable. Handles are assigned sequentially, but you should always compare to the known main handle.
- Using
quit()instead ofclose().quit()ends the entire session, whileclose()only closes the current window. - Not waiting for the new window to load. Use
WebDriverWaitto wait for the expected handle count. - Mixing up
getWindowHandle()(singular, current) andgetWindowHandles()(plural, all).
Tips
- Always store the main window handle at the start—it’s your anchor.
- When opening multiple tabs, keep an array of handles and switch by index or by checking the URL/title.
- Use
WebDriverWaitto wait for the number of handles to increase before switching. - If you need to switch to a window with a specific title, loop through handles and check
getTitle(). - For pop-ups that are not new windows but alerts, use the alert API instead of window handles.
Troubleshooting
NoSuchWindowException: The handle you’re trying to switch to doesn’t exist. This often happens after closing a window. Re-fetch the handles and switch to a valid one.
StaleElementReferenceException: The element you were interacting with is no longer attached to the DOM, often because you switched windows. Re-locate the element after switching.
TimeoutException: The new window didn’t open within the wait time. Increase the timeout or check if the pop-up was blocked by the browser. Disable pop-up blockers in your browser capabilities.
Cannot switch to alert: If you see ‘NoAlertPresentException’, the alert may have already been handled or never appeared. Use a wait for alert presence.
Multiple windows but same handle: Sometimes a new tab reuses the same window handle if the browser is misconfigured. Ensure you’re using a recent browser driver and that the browser is not in compatibility mode.
Frequently Asked Questions
How do I switch to a new tab without closing it?
Just switch to its handle and do your work. To return to the original, switch back to the main handle. No need to close unless you’re done.
Can I open a new window instead of a tab?
Yes, use window.open('url', '_blank') in JavaScript. Some browsers may open a tab by default, but the behavior is the same for Selenium—you get a new handle.
Why does my script fail when a pop-up appears?
Pop-ups (alerts) are not windows. Use switchTo()->alert() to handle them. If it’s a new browser window, you need to switch to its handle.
How do I wait for a new window to open?
Use WebDriverWait with a condition that checks if the count of handles is greater than before. Example:
$wait->until(function($driver) use ($mainWindow) {
return count($driver->getWindowHandles()) > 1;
});
Is there a way to switch to a window by its title?
Yes, loop through all handles, switch to each, check getTitle(), and break when it matches. This is useful when you don’t know the order.
What if the new window closes immediately?
This may happen if the page has a script that closes it. You can try to prevent it by using executeScript('window.open(...)') and immediately switching, or use a wait to catch it before it closes.
Related
General steps for current mainstream versions; menus can differ by device and version. See the disclaimer or report an error.
More in this bed
- Access Your Computer From Anywhere: Step-by-Step
- How to Get More Disk Space on Mac: 12 Fixes
- Wii Browser Games With a USB or Bluetooth Controller
- Delete Focus on iPhone: Quick Steps
- Open System Configuration in Windows 10: 7 Ways
- How to Connect VPN: Step-by-Step Setup Guide