Open In App

How to Perform Right-Click using Java in Selenium?

Last Updated : 23 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

While automating a website for testing there is always required to perform some right-click or other user actions on the page.  These user actions are one of the most commonly used actions during automation, so selenium provides a way to perform these user actions by the Actions class.

How to Perform Right Click using Actions Class

When a user performs a right click using the mouse on a particular element to perform some actions is called a right click. We are daily using this user action mostly on File Explorer, For example, to rename a file or delete a file we perform right-click and select an option.

 

Right Click in Selenium

Let’s see how to perform the right click using Selenium. Selenium Webdriver API does not support the user’s actions like Mouse hover, right-click, context-click, and double-click. That is where the Actions class came to use, The actions provided by this class are performed by an API called Advanced user interaction in selenium webdriver.

Action class present in the package,

“org.openqa.selenium.interactions package”

Let’s see how to use the Actions class to Right Click an element:

Instantiate an object for the Actions class 

Actions action = new Actions(driver);

After creating the object we have to locate the web element

WebElement element=driver.findElement(locator);

Using the “ContextClick() method” from the Actions class to perform the Right click. Context Click methods navigate the mouse pointer to the middle of the web Element and then perform the right-click action in that web element.

action.contextClick(webElement).perform();

Example

In this example, we are navigating to the URL “https://demoqa.com/buttons” and performing the Right click on the “Right click” button. 

Java




public class Geeks {
  
    public void geekforgeeks()
    {
  
        ChromeDriver driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.get("https://demoqa.com/buttons");
        WebElement element
            = driver.findElement(By.id("rightClickBtn"));
        Actions action = new Actions(driver);
        action.contextClick(element).perform();
  
        Thread.sleep(5000);
        driver.close();
    }


Code Explanation

Initially, we opened the browser and navigated to the URL

 ChromeDriver driver = new ChromeDriver();
 driver.manage().window().maximize();
 driver.get(“https://demoqa.com/buttons”);

After that, we locate the web element where we have to perform the “Right Click”. Then, We initialize the Action class and performed “Right click” on the web element.

 Actions action=new Actions(driver);
 action.contextClick(element).perform();

Output

Right-click is performed and the result will be displayed.

 


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads