Navigate back and forward in browser


During automation we are at times required to move back to the previuos page or move forward to the next page in browser history. In this post we will learn to perform these operations using driver.navigate command.

Navigate back in browser history

driver.navigate().back();

Navigate forward in browser history

driver.navigate().forward();

Sample code for demonstration

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

	//Setting system property required for launching chrome browser
	System.setProperty("webdriver.chrome.driver", "driverExecutables\\chromedriver.exe");

	//Launching chrome browser
	WebDriver driver = new ChromeDriver();

	//Navigating to the desired website
	driver.get("http://artoftesting.com/sampleSiteForSelenium.html");

	//Used for demo purpose only, not required
	Thread.sleep(4000);

	//Clicking a link
	WebElement artOfTestingLogo = driver.findElement(By.cssSelector("div.navbar-header"));
	artOfTestingLogo.click();

	//Navigating back in browser 
	driver.navigate().back();

	//Used for demo purpose only, not required
	Thread.sleep(4000);

	//Navigating forward in browser 
	driver.navigate().forward();

}