1

I used the below code options to open a hyperlink in the same window and a different tab, but every time the link will open in a different window.

1)

String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL,Keys.RETURN);   
driver.findElement(By.linkText(linkText)).sendKeys(selectLinkOpeninNewTab);  

2)

Actions act = new Actions(driver);  
act.moveToElement(element).doubleClick(element))).build().perform();  

3)

Actions act = new Actions(driver);
act.contextClick(driver.findElement(By.xpath(element)))
    .sendKeys(Keys.ARROW_DOWN)
    .sendKeys(Keys.ARROW_DOWN)
    .sendKeys(Keys.RETURN)
    .build()
    .perform(); 

Expecting link should be open in the same window different tab, but every time it is opening in the new window.

Please help.

Dmitriy Popov
  • 2,150
  • 3
  • 25
  • 34
Sridhar N
  • 11
  • 1
  • You can try to refer this link may help to solve your issue. Ref: https://stackoverflow.com/questions/22820527/how-to-open-new-tab-in-ie-using-selenium-java-and-open-a-url-in-that-tab-not – Deepak-MSFT Jul 02 '19 at 15:01

1 Answers1

0

I wouldn't recommend this approach as keyboard manipulation is definitely not something you want as it will be the major constraint violating Parallel Testing Best Practices, to wit you will not be able to run your tests in Selenium Grid

I would suggest going for an alternative approach to wit:

  1. Extract href attribute from the link
  2. Open a new tab using Window.open() function via driver.executeScript() function
  3. Switch to the new tab using driver.switchTo().window() function

Example code:

WebElement link = driver.findElement(By.linkText(linkText));
String href = link.getAttribute("href");
driver.executeScript("window.open('" + href + "');");
driver.switchTo().window(driver.getWindowHandles().stream().reduce((f, s) -> s).orElse(null));
System.out.println(driver.getTitle()); // at this point you should see the new page title
Dmitri T
  • 159,985
  • 5
  • 83
  • 133