简体   繁体   中英

Handling right click menu items in selenium java

I want to right click and go the 5th option that is "copy link address".

I have tried the following code and this is the only thing i could i could find on then internet

    Actions actions = new Actions(driver);
   WebElement elementLocator = driver.findElement(By.xpath("//*[(@id = \"u_0_1n\")]"));
     TimeUnit.SECONDS.sleep(2); 
   actions.contextClick(elementLocator).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.RETURN).build().perform();

This code actually scrolls the page downward instead of moving down the right click menu as if the right click menu was never there.

Using context clicks is not something I would recommend as it violates Parallel Testing Best Practices

The tests need to be small, atomic, and autonomous and your current approach assumes that the browser has to be in focus. It means that you will neither be able to do anything while the test is running nor run the tests in parallel.

So instead I would suggest:

  1. Extract href attribute from the link you want to click
  2. Use JavascriptExecutor and Window.open() function in order to open the link in the new tab
  3. Switch to the new tab

Example code:

WebElement link = driver.findElement(By.xpath("//*[(@id = \"u_0_1n\")]"));
String url = link.getAttribute("href");
driver.executeScript("window.open('" + url + "');");
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.numberOfWindowsToBe(2));
driver.switchTo().window(driver.getWindowHandles().stream().reduce((f, s) -> s).orElse(null));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM