</>

Technology

Selenium

Difficulty

Intermediate

Interview Question

How to perform right click (context click) in Selenium?

Use Actions.contextClick(element) to simulate a right-click mouse event, which triggers context menus.

Answer

Use Actions.contextClick() to simulate a right-click event.

Basic right click:

Java
WebElement element = driver.findElement(By.id("fileItem"));
Actions actions = new Actions(driver);
actions.contextClick(element).perform();

Right click then select a context menu option:

Java
WebElement element = driver.findElement(By.id("fileIcon"));
Actions actions = new Actions(driver);
actions.contextClick(element).perform();

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));
WebElement deleteOption = wait.until(
    ExpectedConditions.elementToBeClickable(By.xpath("//li[text()=''Delete'']"))
);
deleteOption.click();

Full working test example:

Java
@Test
public void rightClickTest() {
    driver.get("https://demoqa.com/buttons");
    WebElement rightClickBtn = driver.findElement(By.id("rightClickBtn"));

    Actions actions = new Actions(driver);
    actions.contextClick(rightClickBtn).perform();

    String message = driver.findElement(By.id("rightClickMessage")).getText();
    Assert.assertEquals(message, "You have done a right click");
}

Follow AutomateQA

Related Topics