Friday, 25 March 2016

How to right click and select value from context menu in Selenium webdriver

We can use Robot class to simulate clicking on the option in context menu. Below code demonstrates how we can right click to open the context menu and then select the option from menu.

@Testpublic void testRightClick() throws Exception{
    System.setProperty("webdriver.chrome.driver", "C:\\Users\\Sagar\\Videos\\chromedriver_win32\\chromedriver.exe");
    driver = new ChromeDriver();
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    driver.manage().window().maximize();
    driver.get("http://www.softpost.org/selenium-test-page/");
    WebElement element = driver.findElement(By.xpath("//td[contains(text(),'First Name')]//following-sibling::td//input"));
    new Actions(driver).contextClick(element).build().perform();
    pressKeyByRobot();
    Thread.sleep(5000);
    driver.close();
    driver.quit();
}

public static void pressKeyByRobot() throws Exception{
    Robot r = new Robot();
    r.keyPress(KeyEvent.VK_DOWN);
    r.keyPress(KeyEvent.VK_DOWN);
    r.keyRelease(KeyEvent.VK_ENTER);
}


Please note that above code will work only when the menu options are fixed and enabled. Above code will click on second enabled option.

Most of the times, working with context menu is simpler than what people think. After opening the context menu, you can identify the options in menu as any other normal selenium web elements and then use click method. Please note that built-in context menu can not be identified as HTML web element as it's not a part of HTML DOM But Most of the custom context menus developed by developers are a part of HTML DOM. So you can definitely go ahead and use selenium API to interact with that kind of menu.

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

No comments:

Post a Comment

Buy Best Selenium Books

Contributors