How to perform right click on an element and open it a new window using Web Driver

Performing right click is possible using selenium web driver. However, there is no direct way to open a new tab or a new window after performing right click.
Here, I am going to explain you that how to perform right click and open a new tab or a new window using web driver.

RightClick

Code to perform Right click and click on “open link in new tab” option

action.contextClick(element).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build().perform();

//action.contextClick(element) command will perform right click
//sendKeys(Keys.ARROW_DOWN) command will move arrow to first option which is "open link in new tab"

Code to perform Right click and click on “open link in new window” option

action.contextClick(element).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build().perform();

//action.contextClick(element) command will perform right click
//sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN) command will move arrow to the second option which is "open link in new window"

Scenario

Lets look at the scenario mentioned below. It will help you to understand this concept :

a) Launch http://www.automate-apps.com
b) Right click on “Selenium Questions” tab.
c) Click on “open link in new window” option.
d) Print title of newly opened page

Example :

import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
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 RightClick {


    @Test
    public void method1() {

        WebDriver driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        driver.get("http://automate-apps.com/");
        System.out.println(driver.getTitle());
        Actions action = new Actions(driver);
        WebElement element = driver.findElement(By.partialLinkText("SELENIUM QUESTIONS"));
        action.contextClick(element).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build().perform();
        Set<String> winid = driver.getWindowHandles();
        Iterator<String> iter = winid.iterator();
        iter.next();
        String tab = iter.next();
        driver.switchTo().window(tab);
        System.out.println(driver.getTitle());
		driver.quit();
    }

}



If you really like the information provided above, please don’t forget to leave the comment. You can also like us on Facebook.

Leave a Reply

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