Changes in Actions class in Selenium 4 (moveToElement is optional now)
In Selenium 3, if you would like to double click an element using Actions class, you have to first move to that element (using moveToElement method) and then double click it.
Similarly, if you would like to click and hold on any element, you have to first move to that element.
However, moveToElement method is optional in Selenium 4.
Let us first quickly look at Selenium 3 approach.
Launch https://www.selenium-tutorial.com/courses and inspect the LIFETIME MEMBERSHIP link as shown below
Also notice that, when you click and hold this link (do not release), the background color becomes little bit dark as shown below
Below is the script using Selenium 3. Notice that, before using clickAndHold() method, we have to first move to the element using moveToElement() method
When we run the script, notice that click and hold action gets applied to the link (see the dark background color)
Next, after clickAndHold, if we now want to release, we have to again use moveToElement() method as shown below
Run the script, notice below that the link gets clicked and gets navigated to next page
Let us now comment selenium 3 code
Below is Selenium 4 code without moveToElement() method
Run, notice that click and hold action gets applied to the link (see the dark background color)
Next, let us release the link (no need for moveToElement() method)
Run, notice below that the link gets clicked and gets navigated to next page
Let us now see doubleClick() method in Selenium 4.
Launch https://www.selenium-tutorial.com/p/automation-testing-courses
Double click ‘Ongoing’, you would see that the background color changes to blue
Let us inspect this header
So we have the below script
Run the script, notice below that double click operation is success
Code snippet
package sel4scripts;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import io.github.bonigarcia.wdm.WebDriverManager;
public class ActionsAPISel4 {
public static void main(String[] args) throws InterruptedException {
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
//driver.get("https://www.selenium-tutorial.com/courses");
driver.get("https://www.selenium-tutorial.com/p/automation-testing-courses");
//WebElement elem = driver.findElement(By.linkText("LIFETIME MEMBERSHIP TO ALL LIVE TRAININGS"));
WebElement elem = driver.findElement(By.tagName("h1"));
Actions act = new Actions(driver);
/*
//Selenium 3
act.moveToElement(elem).clickAndHold().build().perform();
act.moveToElement(elem).release().build().perform();
*/
//Selenium 4
//act.clickAndHold(elem).build().perform();
//act.release(elem).build().perform();
act.doubleClick(elem).build().perform();
}
}
Thank you for reading!