Saturday, September 14, 2019

Post#63.ContextClick in Selenium


ContextClick:
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.
Consider you want to Right Click on “TestingBar Logo” and Select one option “Open Link in New Tab” as shown in below image.


Script:
package sujoy;
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.Action;
import org.openqa.selenium.interactions.Actions;

public class Locators {

public static void main(String[] args) {

WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://www.testingbar.com/");
//Locate the element on which you want to Right Click
WebElement element = driver.findElement(By.xpath("//*[@id='masthead']/div/div[1]/a/img"));

Actions act=new Actions(driver);
act.contextClick(element).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build().perform();
}
}

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. 


No comments:

Post a Comment