How to perform right click using Selenium ChromeDriver?


We can perform right click using Selenium ChromeDriver. On right clicking on a webelement, the context menu gets displayed. For example, if we right click on a text area, an additional menu with several options come up.

Actions class in Selenium is responsible for simulating this mouse operation. The Actions class provides the contextClick() method to carry out this action and select any option from the context menu.

To perform this entire operation, we shall first move the mouse to the middle of the element with moveToElement() method, then apply contextClick() method. Furthermore, we have to execute the build() method to execute the two actionsand then perform() method to actually perform the actions.

We have to add the import org.openqa.selenium.interactions.Actions package to our code for using the methods under Actions class.

Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;

public class RightClickOperation{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/index.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // identify element
      WebElement l=driver.findElement(By.xpath("//*[text()='Library']"));
      // Actions class with moveToElement() and contextClick()
      Actions a = new Actions(driver);
      a.moveToElement(l).contextClick().build().perform();
      driver.quit();
   }
}

Output

Updated on: 18-Sep-2020

555 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements