In this tutorial, we will concentrate on the Navigation in Selenium. Navigation generally refers to moving from one page to another. This can be performed by clicking a link or by JavaScript. Another way to navigate to other browsers is to click on back arrow or forward arrow of the web page.
You know that Selenium WebDriver click function will be working only inside web page like inside DOM. But the back and forward arrow are on the browser level.
How you will automate this navigation activity in selenium WebDriver?
Yes, You can achieve this target by using Selenium WebDriver. Selenium WebDriver provides several methods to automate Navigation. Some of them are back(), to(String arg0), forward(), refresh(), notify(), notifyAll() etc. Let’s discuss some of them below.
to(String arg0);
This method loads a new web page in an existing browser. It will take a single parameter of type string and returns void.
driver.navigate().to(“www.testinglpoint.com“);
Note: If you will notice the syntax, the navigate().to will do the same functionality same as driver.get(“URL”)
forward():
This method will click the forward button in the existing browser. So it will take you to the next page based on the browser history.
driver.navigate().forward();
back()
This method will click the back button of the current browsers. So this will take you to the previous page based on the browser history.
driver.navigate().back();
refresh():
This method will refresh your current browser. So this will not accept any parameter or not return nay value.
driver.navigate().refresh();
Example with Scenario
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.remote.DesiredCapabilities; public class TestingLPointNavigation { public static void main(String[] args) { // System Property for Gecko Driver System.setProperty("webdriver.gecko.driver","D:\\GeckoDriver\\geckodriver.exe" ); DesiredCapabilities capabilities = DesiredCapabilities.firefox(); capabilities.setCapability("marionette",true); WebDriver driver= new FirefoxDriver(capabilities); // Launch Website driver.navigate().to("https://www.testinglpoint.com"); //Click on the Link Text using click() command driver.findElement(By.linkText("Selenium")).click(); //Go back to Home Page driver.navigate().back(); //Go forward to Registration page driver.navigate().forward(); // Go back to Home page driver.navigate().to("https://www.testinglpoint.com/selenium/"); //Refresh browser driver.navigate().refresh(); //Closing browser driver.close(); } }
In this example we have used the back() to the driver object to navigate to the previous page of the current page. Like back(), we have used forward() with driver object to navigate to the next page of the current page. If the next page or previous page is not exist or disabled then this will not naviagte to any page . This will stay in the current page.