Hello friends, quite often during automation we need to right-click or context-click an element. Usually, this action is followed up by pressing the UP/DOWN arrow keys and ENTER key to select the desired context menu element.
Check our tutorial on pressing the non-text keys in Selenium – Pressing ARROW KEYS, FUNCTION KEYS and other non-text keys in Selenium.
To right click in Selenium, we make use of the Actions class. The Actions class provided by Selenium Webdriver is used to generate complex user gestures including right click, double click, drag and drop, etc.
Content
Code Snippet to Right click in Selenium
Actions action = new Actions(driver);
WebElement element = driver.findElement(By.id("elementId"));
action.contextClick(element).perform();
Here, we are instantiating an object of the Actions class. After that, we pass the WebElement to be right-clicked as a parameter to the contestClick() method present in the Actions class. Then, we call the perform() method to perform the generated action.
Sample Code to right-click an Element
For the demonstration of the right-click action, we will be launching Sample Site for Selenium Learning. Then we will right-click a textbox after which its context menu will get displayed, asserting that right click action is successfully performed.
package seleniumTutorials;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
public class RightClick {
public static void main(String[] args) throws InterruptedException{
WebDriver driver = new FirefoxDriver();
//Launching Sample site
driver.get("https://artoftesting.com/samplesiteforselenium");
//Right click in the TextBox
Actions action = new Actions(driver);
WebElement searchBox = driver.findElement(By.id("fname"));
action.contextClick(searchBox).perform();
//Thread.sleep just for user to notice the event
Thread.sleep(3000);
//Closing the driver instance
driver.quit();
}
}
That’s all we have in this post, share it will your friends. If you have any questions please comment below. Check out the complete Selenium tutorial here.
why am i getting exceptions in all of your codes??
You can share the exception here, in all probability it will be due to some configuration issue or Selenium and browser version compatibility issue.
Hi Kuldeep Rana nice tutorial, I seen small spelling mistake of contestClick() method after the code snippet of Right click.