How to create right click using selenium?

SeleniumAutomation TestingTesting Tools

The right click is performed on any element on the web page to display its context menu. For example, if we right click on an edit box, a new menu with multiple options gets displayed.

Selenium uses the Actions class to perform the right click action. The contextClick() is a method under Actions class to do the right click and once the menu opens, we can select an option from them via automation.

First we need to move the mouse to the middle of the element with moveToElement() method, then do the right click. Next with build() method we shall carry out the composite actions. Finally the perform() method actually performs the actions.

We need to import org.openqa.selenium.interactions.Actions in our code to use Actions class and its methods.

Example

Code Implementation.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
public class RightClick{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/index.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // identify element
      WebElement l=driver.findElement(By.id("gsc-i-id1"));
      // Actions class with moveToElement() and contextClick()
      Actions a = new Actions(driver);
      a.moveToElement(l).contextClick().build().perform();
      driver.quit();
   }
}

Output

raja
Published on 28-Aug-2020 15:54:15
Advertisements