WebDriver Navigation Commands – Navigate, Forward, Back, Refresh in Selenium WebDriver

HOME

1) Navigate

This command loads a new web page in the current window as mentioned in the argument. This command accepts a string parameter and returns nothing.

This command performs the same action as the get() command.

Syntax:

to(String arg0):void

Command:

driver.navigate().to(URL);

2) Forward

This command acts as the same as clicking on the Forward button of any web browser. This command does not require any parameter, and void means return nothing. 

Syntax:

forward(): void 

Command:

driver.navigate().forward();

3) Back

This command acts the same as clicking on the Back button of any web browser. This command does not require any parameter, and void means return nothing. 

Syntax:

back(): void

Command:

driver.navigate().back();

4) Refresh

This command refreshes the current page. This command does not require any parameter, and void means return nothing. 

Syntax:

 refresh(): void 

Command:

driver.navigate().refresh();

How to use Navigation Commands in Selenium WebDriver:

  • Create an instance of ChromeDriver() to handle Navigation commands.
  • Wait until Page Load.
  • Navigate to URL – https://selenium.dev
  • Navigate to another URL.
  • Navigate to the back page.
  • Navigate to the forward page.
  • Refresh the current page.
  • Close the browser

import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

public class navigationCommandsDemo {
	
	public static void main(String[] args) throws InterruptedException {

		ChromeOptions options = new ChromeOptions();
		options.addArguments("--start-maximized");
		options.setImplicitWaitTimeout(Duration.ofSeconds(10));
		
		WebDriver driver = new ChromeDriver(options);
        driver.navigate().to("https://selenium.dev");
        
        //Get the Title of web page
        String PageTitle= driver.getTitle();
        System.out.println("Title of Page 1 is : " + PageTitle);    
        
        Thread.sleep(2000);
        System.out.println("Navigate to New Page 2");
        driver.findElement(By.xpath("//*[@id='main_navbar']/ul/li[4]/a/span")).click();

        Thread.sleep(2000); 
        System.out.println("Navigate back to Old Page 1");
        driver.navigate().back();
 
        Thread.sleep(2000);
        System.out.println("Navigate forward to New Page 2");    
        driver.navigate().forward();
    
        Thread.sleep(2000);
        System.out.println("Refresh the existing page");    
        driver.navigate().refresh();
        
        //quit the browser
        driver.quit();
	}

}

Leave a comment