Sunday, March 17, 2013

How to right click and choose an option using Selenium WebDriver

There is no direct way to choose an option after right clicking using Selenium WebDriver.

For Ex: what i mean here is say you open google.com
and then right click on "About Google" and have to choose "Open Link in new Tab"

In Selenium WebDriver there is no direct way to do this.

The work around is clicking {DOWN} button. But there is a disadvantage in this approach, suppose if your options dynamically change then this approach wont work.

Here is the sample code for the above approach:

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


public class RightClickAndChooseAnOption
{
    public static void main(String[] args)
    {
        WebDriver driver=new FirefoxDriver();
        driver.navigate().to("http://www.google.com");
       
        driver.manage().window().maximize();
       
        WebElement oWE=driver.findElement(By.linkText("About Google"));
       
        Actions oAction=new Actions(driver);
        oAction.moveToElement(oWE);
        oAction.contextClick(oWE).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build().perform();
       
    }

}

1 comment:

  1. Are you sure we can't choose an option with the option name after right clicking using Selenium WebDriver? Im searching for it for a week. It would be helpful if I get this
    Thanks,
    Sandeep

    ReplyDelete

Note: Only a member of this blog may post a comment.