
In some scenarios, we may need to do right click action on an element to do some actions. For Example: Let’s take a very common scenario that we used frequently in Gmail, i.e. performing right click on any mail in the inbox opens a menu displaying the options like Reply, Delete, Reply All, etc. Out of which any option can be selected to perform the desired action. In Selenium one of the most commonly used methods of is contextClick(WebElement), which is used to perform the Right Click action.
Manual Actions
- Launch the web browser and open the application
- Find the required element and do right click on the element
- Go to the options ‘copy’ and get the text of it and print it
- Close the browser
Selenium WebDriver Steps
package automationTestingLab;
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;
public class RightClick {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","F:\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
// Open the required URL
driver.get("http://swisnl.github.io/jQuery-contextMenu/demo.html");
// To maximize the browser
driver.manage().window().maximize();
// Create an object 'action' of an Actions class
Actions action = new Actions(driver);
// Find the web element on which we perform right click
// We need to pass that web element as argument on context click method
WebElement rightClickElement = driver
.findElement(By.xpath("//span[@class='context-menu-one btn btn-neutral']"));
// contextClick() method to do right click on the element
action.contextClick(rightClickElement).build().perform();
// Here we can perform any action on context click, I just get the copy and
// print it to console
WebElement getCopy = driver.findElement(By.xpath("/html[1]/body[1]/ul[1]/li[3]/span[1]"));
// getText() method to get the text value
String GetText = getCopy.getText();
// To print the value
System.out.println(GetText);
// To close the browser
driver.close();
}
}