driver.get() vs driver.navigate().to()
driver.get() :
Method signature : driver.get(String URL_to_launch) . WebDriver interface provides this method to launch a browser:
public class LaunchBrowser{
public static void main(String args[]){
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com"); //launch the browser
}
}
driver.navigate().to() :
Method signature : driver.navigate.to(String URL_to_launch). Navigation is an inner static interface in WebDriver. It has following methods :
public class NavigationMethods{
public static void main(String args[]){
WebDriver driver = new ChromeDriver();
//driver.navigate().to("https://www.google.com"); // OR,
driver.navigate().to(new URL("https://www.google.com"));
//driver.navigate().to() is an overloaded method which takes both URL type
//and String type of parameters
driver.navigate().refresh(); //refreshes the page
driver.navigate().forward(); //navigates forward one item in the browser
//history
driver.navigate().back(); // navigates back one item in the browser
//history
}
}
Difference between, get() and navigate().to() :
WebDriver method get(String URL) is defined in the child class which is RemoteWebDriver class.
WebDriver.Navigation provides the overloaded; to(String url) and to(URL url), which does the same thing as the get(String url) method! Just that, using navigate() method, we can navigate back and forth on the browser within the same session.
StaleElementReferenceException :
Let's see the below code :
public class StaleElementRefException {
public static void main(String[] args){
WebDriver driver = new ChromeDriver();
driver.get("https://practicetestautomation.com/practice-test-login/");
WebElement username = driver.findElement(By.id("username"));
WebElement password = driver.findElement(By.id("password"));
username.sendKeys("student");
driver.navigate().refresh();
password.sendKeys("Password123");
}
And it throws below exception :
Let's understand why. When the browser is loaded, the driver has access to the located elements. When the page gets refreshed, the DOM got updated and driver lost the access to the element. In some cases, it might happen that, while performing some action an element, the DOM got reloaded (web page got refreshed) and out script starts throwing exceptions!
How to avoid it :
A simple solution is to try finding the element again before performing any actions on it, as shown below:
public class StaleElementRefException {
public static void main(String[] args){
WebDriver driver = new ChromeDriver();
driver.get("https://practicetestautomation.com/practice-test-login/");
WebElement username = driver.findElement(By.id("username"));
WebElement password = driver.findElement(By.id("password"));
username.sendKeys("student");
driver.navigate().refresh();
password = driver.findElement(By.id("password")); //find the element again
password.sendKeys("Password123");
}
Happy learning!