on a web page, have a button with a link embedded in it. “how to click a button link in new tab” using selenium webdriver? Please note it's a button

On a web page, have a button with a link embedded in it. I have coded for clicking the link and the link is getting open up in new browser window. But, i want to open up it in new tab. i tried sendKeys(Keys.CONTROL +”t”), which is opening new tab, but my button link is not getting open up in new tab. instead it is still open up in new browser window.

“how to click a button link in new tab” using selenium webdriver? Please note it is a link embedded in button.

1 answer

  • answered 2018-07-11 05:23 Shivam Mishra

    You can first extract the link attribute from your button and then create a new tab and load that URL. (The solution below is in JAVA)

    1) Extract the link from the button:

    For ex, if the URL is inside action attribute -

    String button_URL = your_button_element.getAttribute("action");
    // you can change the attribute according to your HTML.
    

    2) Then open a new tab:

    WebElement body_element = driver.findElement(By.tagName("body"));
    body_element.sendKeys(Keys.CONTROL +”t”);
    

    3) Then switch to the newly opened tab:

    List <String> opened_tabs = driver.getWindowHandles();
    driver.switchTo().window(opened_tabs.get(1));
    

    4) Then simply load the URL you captured earlier:

    driver.get(button_URL);
    //do your stuff on the new tab.
    

    5) After you are done with the new tab, close it and switch back to the original tab:

    driver.close();
    driver.switchTo().window(opened_tabs.get(0));