Selenium Java - Perform Context (Right) Click using Actions Class

Selenium Java - Perform Context (Right) Click using Actions Class
Introduction
In this blog, we'll dive into using the Actions class in Selenium WebDriver with Java to do a context (right) click on a specific element. This is super handy when you're testing features that pop up with a right-click, like context menus or custom actions.
Performing Context Click using Actions Class
Below is a complete Selenium code example that demonstrates how to perform a context click using the Actions class.
java
package sa.Demo.SeleniumPractice;
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;
import org.testng.annotations.Test;
import java.time.Duration;
public class Selenium_078 {
/****
* Sample Code Definition :- Selenium - Context Right Click
* Developed By :- Pankaj Kumar
* Date of Creation :- 15-June-2024
* Project :- SAJVSAUTO - Java [Web / Mobile / API]
* SA_BLOG_CODE :- SAJVSAUTO_078
*/
@Test
public void Selenium_078() throws InterruptedException {
System.out.println("Selenium - Context Right Click");
// Open Chrome Browser
WebDriver driver = new ChromeDriver();
// Maximize the Browser Window
driver.manage().window().maximize();
// Setup the implicit Wait
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(30));
// Open the URL
driver.get("https://practice.solveautomation.in");
// Click the Register Link
driver.findElement(By.xpath("//a[normalize-space()='Register']")).click();
// Wait for 5 Seconds
Thread.sleep(5000);
// Perform Context (Right) Click on the Register Header
WebElement element = driver.findElement(By.xpath("//h1[normalize-space()='Register']"));
Actions actions = new Actions(driver);
actions.contextClick(element).build().perform();
// Wait for 5 Seconds
Thread.sleep(5000);
// Quit the Driver
driver.quit();
}
}
Explanation
Browser Setup: Configures ChromeDriver, maximizes the browser window, and applies an implicit wait.
Page Interaction: Opens the target URL, navigates to the registration page, and identifies the element to be right-clicked.
Actions Class: Uses the Actions class to perform a context click on the specified element.
- The
contextClick()
method is used to simulate a right-click operation.
- The
Thread.sleep(): Pauses (
Thread.sleep()
) are included for clarity during observation (optional for test cases).Driver Cleanup: Ensures proper closure of the WebDriver session by quitting the driver after execution.
Conclusion
Using the Actions class in Selenium to perform context clicks is an easy and effective way to automate right-click actions. This method lets you test context-specific features with ease.
Subscribe to my newsletter
Read articles from Pankaj Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
