0
0
Selenium Javatesting~5 mins

Navigation (back, forward, refresh) in Selenium Java

Choose your learning style9 modes available
Introduction

Navigation helps you move between web pages during testing. It lets you go back, forward, or refresh pages like a real user.

When you want to test if the back button returns to the previous page correctly.
When you need to check if the forward button loads the next page after going back.
When you want to reload a page to see if it updates or resets properly.
When testing multi-step forms where users navigate back and forth between pages.
When verifying that page refresh keeps or resets data as expected.
Syntax
Selenium Java
driver.navigate().back();
driver.navigate().forward();
driver.navigate().refresh();

Use driver.navigate() to access navigation methods.

These methods simulate browser buttons: back, forward, and refresh.

Examples
Goes back to the previous page in browser history.
Selenium Java
driver.navigate().back();
Moves forward to the next page if you went back before.
Selenium Java
driver.navigate().forward();
Reloads the current page to get fresh content.
Selenium Java
driver.navigate().refresh();
Sample Program

This test opens two pages, goes back to the first, then forward to the second, and refreshes the page. It prints the current URL after back and forward navigation.

Selenium Java
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class NavigationTest {
    public static void main(String[] args) throws InterruptedException {
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
        WebDriver driver = new ChromeDriver();

        // Open first page
        driver.get("https://example.com/page1");
        Thread.sleep(1000); // wait 1 second

        // Open second page
        driver.get("https://example.com/page2");
        Thread.sleep(1000); // wait 1 second

        // Go back to first page
        driver.navigate().back();
        Thread.sleep(1000);
        System.out.println("Back URL: " + driver.getCurrentUrl());

        // Go forward to second page
        driver.navigate().forward();
        Thread.sleep(1000);
        System.out.println("Forward URL: " + driver.getCurrentUrl());

        // Refresh the current page
        driver.navigate().refresh();
        System.out.println("Page refreshed.");

        driver.quit();
    }
}
OutputSuccess
Important Notes

Always wait a little after navigation to let the page load before interacting.

Use driver.getCurrentUrl() to check which page is loaded after navigation.

Remember to close the browser with driver.quit() to free resources.

Summary

Navigation methods let you move back, forward, or refresh pages like a user.

Use driver.navigate() with back(), forward(), and refresh().

Check the current page URL to confirm navigation worked as expected.