0
0
Selenium Javatesting~5 mins

Context click (right click) in Selenium Java

Choose your learning style9 modes available
Introduction

Context click lets you simulate a right-click on a webpage element. This helps test menus or actions that appear on right-click.

Testing a custom context menu on a webpage.
Checking if right-click options work correctly.
Verifying that right-click triggers expected behavior.
Automating tasks that require right-click actions.
Testing browser default context menu is disabled.
Syntax
Selenium Java
Actions actions = new Actions(driver);
actions.contextClick(element).perform();

You need to import org.openqa.selenium.interactions.Actions.

Always call perform() to execute the action.

Examples
Right-click on an element with id 'box'.
Selenium Java
WebElement box = driver.findElement(By.id("box"));
Actions actions = new Actions(driver);
actions.contextClick(box).perform();
Right-click at the current mouse location.
Selenium Java
Actions actions = new Actions(driver);
actions.contextClick().perform();
Sample Program

This test opens a demo page, right-clicks a button, and checks if the context menu appears.

Selenium Java
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 ContextClickTest {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
        WebDriver driver = new ChromeDriver();
        try {
            driver.get("https://swisnl.github.io/jQuery-contextMenu/demo.html");
            WebElement button = driver.findElement(By.cssSelector("span.context-menu-one.btn.btn-neutral"));
            Actions actions = new Actions(driver);
            actions.contextClick(button).perform();
            WebElement menu = driver.findElement(By.cssSelector("ul.context-menu-list.context-menu-root"));
            if(menu.isDisplayed()) {
                System.out.println("Context menu appeared - Test Passed");
            } else {
                System.out.println("Context menu did not appear - Test Failed");
            }
        } finally {
            driver.quit();
        }
    }
}
OutputSuccess
Important Notes

Make sure the element is visible and enabled before right-clicking.

Use explicit waits if the context menu takes time to appear.

Right-clicking outside elements may trigger browser default menus.

Summary

Context click simulates a right-click on a web element.

Use Actions.contextClick(element).perform() to do this.

It helps test custom right-click menus and related behaviors.