Sometimes, web elements require a right-click (context click) to open a context menu or perform specific actions. Selenium WebDriver provides the Actions class to handle advanced user interactions such as right-clicking.
- Always call
.perform()at the end of the action chain to execute the action. contextClick()is used for right-clicking.
I am providing example script below to handle right click with selenium and java
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.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class RightClickTest {
WebDriver driver;
@BeforeClass
public void setUp() {
// Set path to ChromeDriver
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
// Initialize WebDriver
driver = new ChromeDriver();
driver.manage().window().maximize();
// Open the target URL
driver.get("https://example.com");
}
@Test
public void testRightClick() throws InterruptedException {
// Locate the element to right-click
WebElement element = driver.findElement(By.id("rightClickButton"));
// Create Actions instance
Actions actions = new Actions(driver);
// Perform right-click (context click) action
actions.contextClick(element).perform();
// Optional: wait to observe the action
Thread.sleep(2000);
}
@AfterClass
public void tearDown() {
// Close the browser
if (driver != null) {
driver.quit();
}
}
}