Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get URL for opened tab Selenium/Java

What I'm tesintg: Go to webpage, click on a link which opens in a new tab. Confirm the URL for the new tab.

I'm doing this in Cucumber/Selenium/Java.

This is my Gherkin

Scenario Outline: The HomePage tourism box links to the correct page

Given I navigate to the HomePage in <language>
When I click on the visit Tourism PEI Button
Then I am taken to the Tourism PEI landing page URL in a new tab

Examples:
  | language |
  | English  |
  | French   |

Code I have for clicking the link:

 @When("^I click on the Visit\\s" + pageElements + "$")
public void iClickFOnTheVisitTourismPEIButton(String element)  {
    pageModel.pageObject(element).click();
    progressObj.wait(1);
}

And code I have tried to get the URL from the new tab. I'm struggling here. Everything I try opens a new tab, then the screen goes blank and says data; in the URL or it will open a new tab on top of the one that already does. I know I'm not really on the right track here. This is just the last thing I have tried.

@Then("^I am\\s*((?:not)?)\\staken to the Tourism PEI landing page URL in a new tab$")
public void iAmTakenToTheTourismPEILandingPageURLInANewTab() {

    WebDriver driver = new ChromeDriver();
    Actions action = new Actions(driver);
    action.keyDown(Keys.CONTROL).keyDown(Keys.SHIFT).sendKeys(Keys.TAB).build().perform();
}

I also tried this

 String currentURL;

       currentURL = driver.getWebDriver().getCurrentUrl();
       if (currentURL.equalsIgnoreCase("https://www.tourismpei.com/")) {
           System.out.println("Matches" + currentURL);
       } else {
           System.out.println("Does not match" + currentURL);
       }

It's taking the original URL and not the new tab...

like image 590
Sowa Avatar asked Dec 24 '22 07:12

Sowa


1 Answers

for (String handle : driver.getWindowHandles()) {
    driver.switchTo().window(handle);
    System.out.println(String.format("handle: %s, url: %s", handle, driver.getWebDriver().getCurrentUrl()));
} 
like image 50
lance-java Avatar answered Jan 11 '23 04:01

lance-java