9

I know there's a

driver.navigate().back()

but that's not what I'm looking for.

Let's say a user is on PageA, they click on a submit button which takes them to a submit page. On that page, there are two buttons: change selection and confirm. Confirm takes them to the next page, but change selection takes them back to the page they were on.

It's not always going to be PageA, a user can be on PageB, PageC, etc. So, I was wondering if there is a way to return the PageFactory of whatever page the user was previously on? I haven't been able to find anything so far

1
  • 1
    Why do you want that rather than finding the appropriate button? If you use the "Change Selection" button, you'll get all the appropriate state information held in the site, where a different method may not maintain the information and cause unexpected results.
    – Kate Paulk
    May 29, 2014 at 16:47

2 Answers 2

4

I had a similar issue; I wanted a base class for my PageObjects that abstracted the navigation between pages in the wizard flow. What I ended up doing was, after clicking any link that would navigate to a new page, I grabbed the current URL and constructed a new page instance based on that to return. Something like:

protected PageObject navigate(WebElement button) {
    button.click();
    PageObject nextPage = getPageFromURL(driver.getCurrentUrl());
    PageFactory.initElements(driver, nextPage);
    return nextPage;
}

where getPageFromURL has a big lookup table of URLs to PageObject classes. Then I could implement meaningful methods like:

public PageObject clickNext() {
    return navigate(nextButton);
}

or:

 public PageObject viewProductDetails(Product p) {
    return navigate(getDetailsButton(p));
}

I hope that helps you with architecting a solution!

7

You can use JavaScript to go back one step in the history of the browser, this should bring you back on the previous page.

driver.executeScript("window.history.go(-1)");

See using JavaScript with Selenium and JavaScript History functions links.

Also see this thread about issue and difference with navigate.back()

1
  • 1
    This answer should actually be using an instance of JavascriptExecutor before the executeScript call. Such as: JavascriptExecutor js = (JavascriptExecutor) driver; Then use js.executeScript("window.history.go(-1)");
    – urbanaut
    Jun 1, 2016 at 15:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.