The context click on WebElement action

The contextClick() method, also known as right-click, is quite common on many web pages these days. It displays a menu similar to this screenshot:

This context menu can be accessed by a right-click of the mouse on the WebElement. WebDriver provides the developer with an option of emulating that action, using the contextClick() method. Like many other methods, this method has two variants as well. One is clicking on the current location and the other overloaded method is clicking on the WebElement. Let's discuss the context of clicking on WebElement here.

The API syntax for the contextClick() method is as follows:

public Actions contextClick(WebElement onElement)

The input parameter is obviously the WebElement that has to be right-clicked, and the return type is the Actions instance. As we do normally, its time to see a code example. If you open the ContextClick.html file, you can right-click on the text visible on the page, and it will display the context menu. Now clicking any item pops up an alert dialog stating which item has been clicked. Now let's see how to implement this in WebDriver, using the following code:

@Test
public void shouldContextClick() {

driver.get("http://guidebook.seleniumacademy.com/ContextClick.html");

WebElement contextMenu = driver.findElement(By.id("div-context"));
Actions actions = new Actions(driver);
    actions.contextClick(contextMenu)
.click(driver.findElement(By.name("Item 4")))
.perform();
}

In the preceding code, first we have right-clicked using the contextClick() method on the WebElement contextMenu, and then left-clicked on Item 4 from the context menu. This should pop up an alert dialog saying Item 4 Clicked.