Home >Java >javaTutorial >How to Switch Between Browser Windows Using Selenium WebDriver?
When you click a button that opens a new browser window with search results, it can be useful to interact with the new window and then return to the original window. Here's how you can achieve this in Selenium WebDriver:
1. Store the Current Window Handle:
First store the handle of the current window into a string variable:
String winHandleBefore = driver.getWindowHandle();
2. Perform the Click Operation:
Perform the operation of clicking the button to open a new window.
3. Switch to the New Window:
Use the getWindowHandles() method to get all open window handles, and then use the switchTo().window() method to switch to New window:
for(String winHandle : driver.getWindowHandles()){ driver.switchTo().window(winHandle); }
4. Perform Actions on New Window:
Perform the required operations in a new window.
5. Close the New Window:
If the new window is no longer needed, close it:
driver.close();
6. Switch Back to Original Window:
Use switchTo() Method to switch back to the original browser (first window):
driver.switchTo().window(winHandleBefore);
7. Continue with Original Window:
Continue with the original browser (first window) to interact.
The above is the detailed content of How to Switch Between Browser Windows Using Selenium WebDriver?. For more information, please follow other related articles on the PHP Chinese website!