[java] Select an Option from the Right-Click Menu in Selenium Webdriver - Java

I am using Selenium webdriver. I am not able to select (say 2nd) option from the Options opened on right click.

In my current code I am able to right click on webElement but could not select an Option from the list that is opened after right click, as it disappears automatically.

Actions action= new Actions(driver);
action.contextClick(productLink).build().perform();

So with this code I am able to right click but the right click menu automatically disappears. I want to select say 2nd Option from Right click menu.

Please Help!!!

This question is related to java selenium-webdriver

The answer is


You might have to move the mouse to any particular location after context click() like this -

Actions action = new Actions(driver);
actions.contextClick(link).moveByOffset(x,y).click().build().perform();

To understand how moveByOffset(x,y) works look here;

I hope this works. You will have to calculate the offset values for x and y;

best way would be to find the size of each option button after right clicking and then if you click on the 2nd option .

x = width of option button/2

y = 2*(size of each option button)


We will take the help of WebDriver action class and perform Right Click. the below is the syntax :

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

Below are the Steps we have followed in the example:

  1. Identify the element
  2. Wait for the presence of Element
  3. Now perform Context click
  4. After that we need to select the required link.

package com.pack.rightclick;

    import org.openqa.selenium.Alert;
    import org.openqa.selenium.By;
    import org.openqa.selenium.NoSuchElementException;
    import org.openqa.selenium.StaleElementReferenceException;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.interactions.Actions;
    import org.openqa.selenium.support.ui.ExpectedConditions;
    import org.openqa.selenium.support.ui.WebDriverWait;
    import org.testng.Assert;
    import org.testng.annotations.AfterClass;
    import org.testng.annotations.BeforeClass;
    import org.testng.annotations.Test;

public class RightClickExample {

    WebDriver driver;

    String URL = "http://medialize.github.io/jQuery-contextMenu/demo.html";

    @BeforeClass
    public void Setup() {
        driver = new FirefoxDriver();
        driver.manage().window().maximize();
    }

    @Test
    public void rightClickTest() {
        driver.navigate().to(URL);
        By locator = By.cssSelector(".context-menu-one.box");
        WebDriverWait wait = new WebDriverWait(driver, 5);
        wait.until(ExpectedConditions.presenceOfElementLocated(locator)); 
        WebElement element=driver.findElement(locator);
        rightClick(element);
        WebElement elementEdit =driver.findElement(By.cssSelector(".context-menu-item.icon.icon-edit>span"));
        elementEdit.click();
        Alert alert=driver.switchTo().alert();
        String textEdit = alert.getText();
        Assert.assertEquals(textEdit, "clicked: edit", "Failed to click on Edit link");
    }

    public void rightClick(WebElement element) {
        try {
            Actions action = new Actions(driver).contextClick(element);
            action.build().perform();

            System.out.println("Sucessfully Right clicked on the element");
        } catch (StaleElementReferenceException e) {
            System.out.println("Element is not attached to the page document "
                    + e.getStackTrace());
        } catch (NoSuchElementException e) {
            System.out.println("Element " + element + " was not found in DOM "
                    + e.getStackTrace());
        } catch (Exception e) {
            System.out.println("Element " + element + " was not clickable "
                    + e.getStackTrace());
        }
    }

    @AfterClass
    public void tearDown() {
        driver.quit();
    }


}

Using python webdriver right click operation

from selenium import webdriver

from selenium.webdriver import ActionChains

import time

driver = webdriver.Chrome()

driver.get("https://swisnl.github.io/jQuery-contextMenu/demo.html")
button=driver.find_element_by_xpath("//body[@class='wy-body-for-nav']")

action=ActionChains(driver)
action.context_click(button).perform()

This is how i could click on the fourth element in the Right click window.

 Actions myAction = new Actions(driver); 
 myAction.contextClick(driver.findElement(By.xpath("//ul/li[1]/a/img"))).build().perform();
 myAction.sendKeys(Keys.ARROW_DOWN).build().perform();
 myAction.sendKeys(Keys.ARROW_DOWN).build().perform();
 myAction.sendKeys(Keys.ARROW_DOWN).build().perform();
 myAction.sendKeys(Keys.ARROW_DOWN).build().perform();
 myAction.sendKeys(Keys.ENTER).build().perform();

Hope this helps


WebElement xx = driver.findElement(By.linkText("your element"));
                Actions action = new Actions(driver);
                System.out.println("To open new tab");
                  action.contextClick(xx).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build().perform();
                    Robot robot = new Robot();
                    robot.keyPress(KeyEvent.VK_DOWN);
                    robot.keyPress(KeyEvent.VK_ENTER);

*Using Robot class you can do this, Try following code:

Actions action = new Actions(driver);
action.contextClick(WebElement).build().perform();
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_DOWN);
robot.keyRelease(KeyEvent.VK_DOWN);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);

[UPDATE]

CAUTION: Your Browser should always be in focus i.e. running in foreground while performing Robot Actions, other-wise any other application in foreground will receive the actions.


Right click can be achieved using Java script executor as well(in cases where action class is not supported):

JavascriptExecutor js = (JavascriptExecutor) driver;

String javaScript = "var evt = document.createEvent('MouseEvents');"
                + "var RIGHT_CLICK_BUTTON_CODE = 2;"
                + "evt.initMouseEvent('contextmenu', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, RIGHT_CLICK_BUTTON_CODE, null);"
                + "arguments[0].dispatchEvent(evt)";

js.executeScript(javaScript, element);

Better and easy way.

Actions action = new Actions(driver);
action.moveToElement(driver.findElement(By.cssSelector("a[href^='https://www.amazon.in/ap/signin']"))).contextClick().build().perform();

You can use any selector at the place of cssSelector.


Instead of attempting to do a right click on a mouse use the keyboard shortcut:

Double click on the element -> hold shift and press F10.

Actions action = new Actions(driver);

//Hold left shift and press F10
action.MoveToElement(element).DoubleClick().KeyDown(Keys.LeftShift).SendKeys(Keys.F10).KeyUp(Keys.LeftShift).Build().Perform();

Here is the code for Right click on a webelement.

Actions actions = new Actions(driver);    
Action action=actions.contextClick(WebElement).build(); //pass WebElement as an argument
            action.perform();

this is better approach and its successful :

Actions oAction = new Actions(driver);
oAction.moveToElement(Webelement);
oAction.contextClick(Webelement).build().perform();  /* this will perform right click */
WebElement elementOpen = driver.findElement(By.linkText("Open")); /*This will select menu after right click */

elementOpen.click();