Welcome to today’s session on Selenium WebDriver Navigational and Window Handle Commands. In the previous classes, we covered WebDriver Commands including Get Methods, Conditional Methods, Browser Commands, and Wait Commands. Today, we’ll explore Navigational Commands and Window Handle Commands, essential tools for managing browser navigation and handling multiple browser windows or tabs in your automation scripts.
Table of Contents
1. Navigational Commands
• Overview
Navigational commands in Selenium WebDriver allow you to control the browser’s navigation, enabling you to move between different pages and manage the browser’s state. These commands are accessible through the navigate()
method provided by the WebDriver instance.
• Key Methods
navigate().to()
Description: Navigates to a specified URL. Functionally similar to the get()
method.
Usage:
driver.navigate().to("https://www.example.com");
Alternative Usage with URL Object:
URL url = new URL("https://www.example.com");
driver.navigate().to(url);
navigate().back()
Description: Simulates the browser’s back button, navigating to the previous page in the browser’s history.
Usage:
driver.navigate().back();
navigate().forward()
Description: Simulates the browser’s forward button, navigating to the next page in the browser’s history.
Usage:
driver.navigate().forward();
navigate().refresh()
Description: Refreshes or reloads the current page.
Usage:
driver.navigate().refresh();
• Differences Between get() and navigate().to()
While both driver.get(String url)
and driver.navigate().to(String url)
can be used to navigate to a web page, there are subtle differences:
- Implementation:
get()
: Directly navigates to the specified URL.navigate().to()
: Internally calls theget()
method but is part of a larger set of navigational commands.
- Parameter Acceptance:
get()
: Accepts only a String URL.navigate().to()
: Accepts both String and URL objects.
- Use Cases:
- Use
get()
for straightforward navigation. - Use
navigate().to()
when you need to navigate using a URL object or when combining with other navigational methods like back, forward, and refresh.
- Use
• Practical Example
Let’s walk through an example to understand navigational commands in action.
Scenario
- Launch the browser and navigate to
"https://demo.nopcommerce.com"
. - Maximize the browser window.
- Click on a link that opens another browser window.
- Navigate back to the previous page.
- Navigate forward to the next page.
- Refresh the current page.
Code Example
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.net.URL;
import java.time.Duration;
public class NavigationalCommandsExample {
public static void main(String[] args) throws Exception {
// Set the path for the ChromeDriver
System.setProperty("webdriver.chrome.driver", "path_to_chromedriver");
// Initialize WebDriver
WebDriver driver = new ChromeDriver();
// Set Implicit Wait of 10 seconds
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
// Maximize Browser Window
driver.manage().window().maximize();
// Navigate to the URL using navigate().to()
driver.navigate().to("https://demo.nopcommerce.com");
// Click on a link that opens a new browser window (e.g., 'Electronics')
WebElement electronicsLink = driver.findElement(By.linkText("Electronics"));
electronicsLink.click();
// Navigate back to the previous page
driver.navigate().back();
// Navigate forward to the next page
driver.navigate().forward();
// Refresh the current page
driver.navigate().refresh();
// Close the browser
driver.quit();
}
}
Explanation:
- Initialization: Sets up the ChromeDriver and initializes the WebDriver instance.
- Implicit Wait: Ensures elements are given up to 10 seconds to appear before throwing an exception.
- Navigation: Demonstrates using
navigate().to()
,navigate().back()
,navigate().forward()
, andnavigate().refresh()
.
2. Window Handle Commands
• Overview
When automating tasks that involve multiple browser windows or tabs, Selenium WebDriver provides methods to handle window handles. Each browser window or tab has a unique identifier (window handle) that allows you to switch control between them.
• Key Methods
getWindowHandle()
Description: Retrieves the unique handle of the current browser window.
Returns: A String representing the window handle.
Usage:
String parentWindowHandle = driver.getWindowHandle();
getWindowHandles()
Description: Retrieves the handles of all open browser windows or tabs.
Returns: A Set<String>
containing all window handles.
Usage:
Set<String> allWindowHandles = driver.getWindowHandles();
• Switching Between Windows
To interact with elements in different browser windows or tabs, you must switch the WebDriver’s focus to the desired window using its handle.
Steps to Switch Windows
-
- Capture the Parent Window Handle:
String parentWindow = driver.getWindowHandle();
-
- Perform Action that Opens a New Window:
WebElement link = driver.findElement(By.linkText("Open New Window"));
link.click();
-
- Capture All Window Handles:
Set<String> allWindows = driver.getWindowHandles();
-
- Iterate Through Window Handles and Switch:
for (String windowHandle : allWindows) {
if (!windowHandle.equals(parentWindow)) {
driver.switchTo().window(windowHandle);
// Perform actions on the new window
}
}
-
- Switch Back to Parent Window:
driver.switchTo().window(parentWindow);
• Practical Example
Let’s implement a scenario to understand window handle commands.
Scenario
- Launch the browser and navigate to
"https://demo.nopcommerce.com"
. - Maximize the browser window.
- Click on a link that opens a new browser window (e.g., “Electronics”).
- Capture and switch to the child window.
- Perform actions in the child window (e.g., verify the title).
- Switch back to the parent window.
- Close specific browser windows based on their titles.
Code Example
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.Set;
import java.util.List;
import java.util.ArrayList;
import java.time.Duration;
public class WindowHandleExample {
public static void main(String[] args) {
// Set the path for the ChromeDriver
System.setProperty("webdriver.chrome.driver", "path_to_chromedriver");
// Initialize WebDriver
WebDriver driver = new ChromeDriver();
// Set Implicit Wait of 10 seconds
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
// Maximize Browser Window
driver.manage().window().maximize();
// Navigate to the URL using navigate().to()
driver.navigate().to("https://demo.nopcommerce.com");
// Click on 'Electronics' link which opens a new window
WebElement electronicsLink = driver.findElement(By.linkText("Electronics"));
electronicsLink.click();
// Capture Parent Window Handle
String parentWindow = driver.getWindowHandle();
// Capture All Window Handles
Set<String> allWindows = driver.getWindowHandles();
// Convert Set to List for easy access
List<String> windowList = new ArrayList<>(allWindows);
// Assuming the second window is the child window
String childWindow = "";
if (windowList.size() > 1) {
childWindow = windowList.get(1);
}
// Switch to Child Window
driver.switchTo().window(childWindow);
// Perform actions in Child Window
String childTitle = driver.getTitle();
System.out.println("Child Window Title: " + childTitle);
// Switch Back to Parent Window
driver.switchTo().window(parentWindow);
String parentTitle = driver.getTitle();
System.out.println("Parent Window Title: " + parentTitle);
// Close Child Window Based on Title
for (String windowHandle : allWindows) {
driver.switchTo().window(windowHandle);
String title = driver.getTitle();
if (title.equals("Electronics - nopCommerce")) { // Replace with actual child window title
driver.close();
}
}
// Close Parent Window
driver.switchTo().window(parentWindow);
driver.quit();
}
}
Explanation:
- Window Handles: Captures the parent and child window handles.
- Switching: Uses
driver.switchTo().window()
to switch between windows. - Closing Specific Windows: Iterates through all window handles, checks the title, and closes the desired window.
• Switching Between Windows
When dealing with multiple windows, especially more than two, it’s efficient to use a loop to iterate through all window handles and perform actions based on specific conditions like window titles.
Example with Multiple Windows
// Assume multiple windows are already opened
Set<String> allWindows = driver.getWindowHandles();
List<String> windowList = new ArrayList<>(allWindows);
// Iterate through each window handle
for (String windowHandle : windowList) {
driver.switchTo().window(windowHandle);
String title = driver.getTitle();
if (title.equals("Desired Window Title")) {
// Perform actions
// e.g., driver.close();
}
}
Explanation:
- Iteration: Loops through each window handle.
- Condition: Checks if the window’s title matches the desired title.
- Action: Performs actions like closing the window or interacting with elements.
3. Assignment
Objective: Apply the navigational and window handle commands learned today to automate interactions on a practice web page.
Scenario
- Navigate to the Practice Page:
- Open the URL: https://testautomationpractice.blogspot.com/
- Perform Search Operation:
- Locate the search box.
- Enter the search string “selenium”.
- Click on the search button.
- Count the Number of Links:
- After the search results load, count and print the number of links displayed.
- Click on Each Link Using a For Loop:
- Iterate through each link.
- Click on the link to open it in a new tab or window.
- Capture Window Handles:
- After opening all links, capture the window handles of all browser windows or tabs.
- Close Specific Browser Windows Based on Title:
- Iterate through each window handle.
- Switch to the window.
- Get the title of the window.
- If the title matches a specific criterion (e.g., contains “Selenium”), close the window.
Submission: Provide your Selenium scripts demonstrating the above tasks. Ensure your code is well-commented to explain each step.
Example Skeleton:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.Set;
import java.util.List;
import java.util.ArrayList;
import java.time.Duration;
public class AssignmentExample {
public static void main(String[] args) {
// Initialize WebDriver
WebDriver driver = new ChromeDriver();
// Set Implicit Wait
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
// Maximize Window
driver.manage().window().maximize();
// Navigate to Practice Page
driver.navigate().to("https://testautomationpractice.blogspot.com/");
// Locate Search Box and Enter Search String
WebElement searchBox = driver.findElement(By.id("Wikipedia1_wikipedia-search-input"));
searchBox.sendKeys("selenium");
// Click on Search Button
WebElement searchButton = driver.findElement(By.id("Wikipedia1_wikipedia-search-form-submit"));
searchButton.click();
// Count Number of Links Displayed
List<WebElement> links = driver.findElements(By.tagName("a"));
System.out.println("Number of links found: " + links.size());
// Click on Each Link to Open in New Tab/Window
for (WebElement link : links) {
String url = link.getAttribute("href");
if (url != null && !url.isEmpty()) {
driver.executeScript("window.open('" + url + "','_blank');");
}
}
// Capture All Window Handles
Set<String> allWindows = driver.getWindowHandles();
List<String> windowList = new ArrayList<>(allWindows);
// Iterate and Close Specific Windows Based on Title
for (String windowHandle : windowList) {
driver.switchTo().window(windowHandle);
String title = driver.getTitle();
if (title.contains("Selenium")) { // Replace with desired condition
driver.close();
}
}
// Switch Back to Parent Window
driver.switchTo().window(windowList.get(0));
// Close Browser
driver.quit();
}
}
Notes:
- Opening Links in New Tabs: Using JavaScript to open links in new tabs ensures that Selenium can handle multiple windows effectively.
- Condition for Closing Windows: Adjust the condition based on the actual titles of the pages you are testing.
4. Best Practices
- Use Implicit Waits Wisely: Apply implicit waits globally for general synchronization but prefer explicit waits for specific conditions.
- Manage Window Handles Efficiently:
- Always capture the parent window handle before opening new windows.
- Use meaningful conditions (like window titles) to switch and perform actions.
- Avoid Hardcoding Values: Instead of hardcoding titles or URLs, consider using variables or configurations to make your scripts more maintainable.
- Clean Up After Tests: Ensure that all opened browser windows are closed at the end of the test to prevent resource leaks.
- Handle Exceptions Gracefully: Implement try-catch blocks to manage unexpected scenarios and ensure that the browser closes even if an error occurs.
- Use Meaningful Locators: When locating elements, use unique and descriptive locators to enhance the reliability of your scripts.
5. Conclusion
Today, we explored Navigational Commands and Window Handle Commands in Selenium WebDriver:
- Navigational Commands:
navigate().to()
: Navigate to a specified URL.navigate().back()
: Navigate to the previous page.navigate().forward()
: Navigate to the next page.navigate().refresh()
: Refresh the current page.
- Window Handle Commands:
getWindowHandle()
: Retrieve the current window’s handle.getWindowHandles()
: Retrieve handles of all open windows.- Switching Between Windows: Using window handles to switch focus between different browser windows or tabs.
Key Takeaways:
- Navigational commands provide control over browser navigation, enabling you to move between pages and manage the browser’s state effectively.
- Window handle commands are essential for managing multiple browser windows or tabs, allowing you to switch context and interact with elements in different windows.
- Combining navigational and window handle commands enhances the robustness and flexibility of your automation scripts, especially in complex web applications.
Next Steps:
- Practice the Assignment: Implement the provided assignment to reinforce your understanding.
- Explore Advanced Window Handling: Learn about handling alerts, frames, and other advanced browser interactions in upcoming sessions.
- Optimize Your Scripts: Incorporate best practices to make your automation scripts more efficient and maintainable.
Happy Automating!