Working with browser navigation

Browsers provide various navigation methods to access web pages from the browser history or by refreshing the current page with the back, forward, and refresh/reload buttons on the browser window's toolbar. The Selenium WebDriver API provides access to these buttons with various methods of WebDriver.Navigation interface. We can test the behavior of the application when these methods are used.

Method

Description

back()

This method moves back to the page in browser history.

forward()

This method moves forward to the page in browser history.

refresh()

This method reloads the current page.

to(String url)

to(java.net.URL url)

This method loads the specified URL in the current browser window.

In this recipe, we will see browser navigation methods.

Getting ready

Create a new test that will get an instance of WebDriver, navigate to a site, and perform some basic actions and verifications.

How to do it...

Let's create a test that calls various navigation methods and checks the behavior of the application in following code example:

@Test
public void testNavigation() {
  driver.get("http://www.google.com");

  // Get the search textbox
  WebElement searchField = driver.findElement(By.name("q"));
  searchField.clear();

  // Enter search keyword and submit
  searchField.sendKeys("selenium webdriver");
  searchField.submit();

  WebElement resultLink = driver.findElement(By.linkText("Selenium WebDriver"));
  resultLink.click();

  new WebDriverWait(driver, 10).until(ExpectedConditions
      .titleIs("Selenium WebDriver"));

  assertEquals("Selenium WebDriver", driver.getTitle());

  driver.navigate().back();

  new WebDriverWait(driver, 10).until(ExpectedConditions
      .titleIs("selenium webdriver - Google Search"));

  assertEquals("selenium webdriver - Google Search", driver.getTitle());

  driver.navigate().forward();

  new WebDriverWait(driver, 10).until(ExpectedConditions
      .titleIs("Selenium WebDriver"));

  assertEquals("Selenium WebDriver", driver.getTitle());

  driver.navigate().refresh();

  new WebDriverWait(driver, 10).until(ExpectedConditions
      .titleIs("Selenium WebDriver"));

  assertEquals("Selenium WebDriver", driver.getTitle());
}

How it works...

The WebDriver.Navigation interface provide back() and forward() to load pages from browser history. These methods represent the back and forward arrow buttons available in any web browser. We can also refresh or reload a page by calling the refresh() method.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.17.27