Right Click (Context Click) in Selenium

Right click or Context click in selenium WebDriver using Actions class-

Sometimes you’ll run into an app that has functionality hidden behind a right-click menu (a.k.a. a context menu). These menus tend to be system level menus that are untouchable by Selenium. So how do you test this functionality?

Right Click (Context Click ) using Actions Class using Selenium WebDriver
We can then select an option from the menu by traversing it with keyboard arrow keys (which we can issue with the Action Builder’s send_keys command).
In Selenium WebDriver to perform right click on any web element is not a complex process. All you have to do is create an instance of Action class and call the methods defined in it to perform the actions you want. Follow the below steps in order to perform right click on any web element:

Below are the Steps we have followed in the example:

    Identify the element
    Wait for the presence of Element
    Now perform Context click
    After that we need to select the required link.

Example –

package learnAboutActionsClass;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class RightClickInSelenium {
 
 public static void main(String[] args){
  
  WebDriver driver = new FirefoxDriver();
  driver.navigate().to("http://automationtalks.com/");
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  driver.manage().window().maximize();
  
  Actions act = new Actions(driver);
  act.moveToElement(driver.findElement(By.xpath("//*[@id='mbtnav']/li[3]/a"))).build().perform();
   act.contextClick(driver.findElement(By.xpath("//*[@id='mbtnav']/li[3]/ul/li[2]/a"))).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build().perform();
  //Switching between tabs using CTRL + tab keys.
    driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");
    //Switch to current selected tab's content.
    driver.switchTo().defaultContent();  
 }

}

Here the method sendKeys(Keys.ARROW_DOWN) is used to select an option from the list. If you will not add this method, the right click on the web element will be performed and the option list which appears after the right click will get disappeared without selecting any option.

We can perform the right click on any web element using the Robot class too. Here you first need to move the mouse to the particular web element and then perform the required action…!!!

Actions class in Selenium WebDrivr

Leave Comment

Your email address will not be published. Required fields are marked *

Looking for learning Framework Development from Scratch? Lookout for Detailed Framework Development videos on YouTube here -

https://www.youtube.com/automationtalks

Get the Framework code at Github Repo: https://github.com/prakashnarkhede?tab=repositories