Right Click and Double Click in Selenium

 

In Selenium with Java, you can perform Right Click (Context Click) and Double Click using the Actions class from the org.openqa.selenium.interactions package.


1. Right Click (Context Click) Example

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;

public class RightClickExample {
    public static void main(String[] args) {
        WebDriver driver = new ChromeDriver();
        driver.get("https://swisnl.github.io/jQuery-contextMenu/demo.html");

        // Find the element to right click
        WebElement element = driver.findElement(By.cssSelector(".context-menu-one"));

        // Create Actions class object
        Actions actions = new Actions(driver);

        // Perform Right Click (Context Click)
        actions.contextClick(element).perform();

        // Optional: Click on a menu item if needed
        WebElement menuItem = driver.findElement(By.cssSelector(".context-menu-item.icon-copy"));
        menuItem.click();

        driver.quit();
    }
}


font-size:14px;

2. Double Click Example

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;

public class DoubleClickExample {
    public static void main(String[] args) {
        WebDriver driver = new ChromeDriver();
        driver.get("https://demo.guru99.com/test/simple_context_menu.html");

        // Find the button to double-click
        WebElement button = driver.findElement(By.xpath("//button[text()='Double-Click Me To See Alert']"));

        // Create Actions class object
        Actions actions = new Actions(driver);

        // Perform Double Click
        actions.doubleClick(button).perform();

        // Handle the alert
        driver.switchTo().alert().accept();

        driver.quit();
    }
}


Important Points:

  • You must call .perform() at the end to actually execute the action.

  • Make sure to import Actions class:

import org.openqa.selenium.interactions.Actions;