About this lesson
Right click (context click) in Selenium Java with Actions contextClick()
Learn Selenium JavaAdvancedActions Class
How it works
actions.contextClick(element).perform() presses and releases the right mouse button over the element, firing mousedown with the right button and then contextmenu. The right-click button on the Buttons page reacts to that right-button mousedown and rewrites its label.
Selenium can only see what the page draws. The browser's own context menu, with items like "Back" and "Inspect", is outside the page and cannot be clicked with WebDriver. Custom context menus that a web app draws in HTML are ordinary elements and can be found and clicked after the right click.
A right click does not block the page the way an alert does. After it, other elements on the page can be found and used as normal.
About the assignment
The starter gives you an Actions object and the right-click button. You read its label, right-click it, and read the label again.
What you will do
- Read the right-click button's label and print it after
Before:. - Right-click it with
contextClick()andperform(). - Read the label once more and print it after
After:.
Common mistakes
Using click()
A left click presses the left button, and the page only reacts to a right-button press, so the label stays the same.
Trying to use the browser's menu
Native menu items cannot be located. Test what the app does on right click, not the browser's menu.
Calling contextClick() without perform()
Nothing happens, and no error says so.
In a real test suite
Web apps with file trees, maps and design canvases often draw their own right-click menus. A test right-clicks the item, waits for the menu element to be visible, then clicks an entry such as Rename.
Lesson 52 double-clicked. Lesson 54 moves to the Drag and Drop page and the harder case of dragging.
Related lessons
- Double Click ActionDouble-click, the other special click on this page.
- Explicit Wait - Element VisibleWait for a custom menu to appear after the right click.
- Drag and Drop with the Actions ClassDrag and drop with Actions.
To try one of these calls on any page without a task, open the Online Selenium Java Compiler.
Starter code
The editor above opens with this code. Fill in the TODO lines, then run and submit it.
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
public class Main {
public static void main(String[] args) throws Exception {
WebDriver driver = new ChromeDriver();
driver.get("https://testkru.com/Elements/Buttons");
Actions actions = new Actions(driver);
WebElement button = driver.findElement(By.id("rightClick"));
// TODO: Print initial text
// TODO: Right-click the button
// TODO: Print text after right-click
driver.quit();
}
}