Additional Browser Commands in Selenium WebDriver

Beyond the basic commands, Selenium WebDriver provides several additional commands to enhance browser automation. These commands allow you to manipulate browser windows, navigate backward and forward in history, and interact with alerts, among other tasks.

These additional commands help in managing browser behavior and enhancing user interactions during automated testing.

Common Additional Browser Commands include:

  1. navigate().to()
  2. navigate().back()
  3. navigate().forward()
  4. switchTo().alert()

1. Navigating to a URL

Use this command to navigate to a specified URL similar to get(), but with additional options for further navigation.

Example:

Java
 driver.navigate().to("http://example.com"); // Navigate to a webpage 

Explanation of Code

  • driver.navigate(): This method returns an instance of Navigation, which allows navigation commands.
  • .to("http://example.com"): This method navigates to the specified URL.
  • After executing this command, the browser will open the specified page, similar to get().

2. Going Back in Browser History

Command: navigate().back(): void
Usage: This command allows the browser to go back to the previous page in the history.

Example:

Java
 driver.navigate().back(); // Goes back to the previous page 

Explanation of Code

  • driver.navigate().back(): This command moves the browser back to the previous page in the browser's history.
  • After executing this command, the browser will load the last visited page.

3. Going Forward in Browser History

Command: navigate().forward(): void
Usage: This command allows the browser to go forward to the next page in the history.

Example:

Java
 driver.navigate().forward(); // Goes forward to the next page 

Explanation of Code

  • driver.navigate().forward(): This command moves the browser forward to the next page in the history, if available.
  • After executing this command, the browser will load the next page in history, if applicable.

4. Handling Alerts

Command: switchTo().alert(): Alert
Usage: Switches to the currently displayed alert, prompt, or confirmation dialog.

Example:

Java
 Alert alert = driver.switchTo().alert(); // Switches to the alert 

Explanation of Code

  • Alert alert: This declares a variable named alert that will reference the currently displayed alert.
  • = driver.switchTo().alert(): This switches the control to the alert displayed by the browser.
  • You can now interact with the alert using the alert variable (e.g., alert.accept() to accept the alert).