Anuj Sharma
Anuj Sharma

Reputation: 66

StaleElementReference Exception

I am struggling with the StaleElementReferenceException problem. I have seen quite a number of discussions on the topic but I haven't been able to find a solution to the issue that I am facing.

The test is to get all the links on the footer of the web page and then verify whether the link is active or not by clicking on it and verifying the title of the page.

First of all, I find & store all the links in an array list. I compare the link name with the values retrieved from the database. Then for each link, I click on it and verify the page title. Then using 'driver.navigate.back()', go back to the original page and continue with the rest of the links.

However, when the control returns back to the page, the StaleElementReferenceException occurs.

Can anyone suggest me a way out of this?

Thanks, Anuj

Upvotes: 0

Views: 381

Answers (3)

Kushal Bhalaik
Kushal Bhalaik

Reputation: 3384

You can handle going and coming to new tab as follows:

String baseHandle = driver.getWindowHandle();

                    Set<String> sr = driver.getWindowHandles();

                    if (sr.size()>1){


                    Set<String> sr1 = driver.getWindowHandles();
                    sr1.remove(baseHandle);


                    Iterator itr = sr1.iterator();

                    driver.switchTo().window(itr.next().toString());

                    System.out.println("Page Title is : " + driver.getTitle());

                    driver.close();

                    driver.switchTo().window(baseHandle);

Upvotes: 0

Gloria Rampur
Gloria Rampur

Reputation: 353

I faced a similar issue, in my case when I type something into a text box it would navigate to another page, so while I come back on the previous page, that object gets stale.

So this was causing the exception, I handled it by again initialising the elements as below -

PageFactory.initElements(driver, Test.class);

So when you navigate back, make sure you are initialising all the elements of that page again, so that the object does not get stale.

Upvotes: 0

Nashibukasan
Nashibukasan

Reputation: 2028

When you are storing all the links in the footer you are grabbing those elements as they are at that point in time. Upon navigating to a different page those particular elements no longer exist. When you return to the back these elements have been created anew.

While the elements are the same via identifiers, they are different instances and thus your old elements in your array are 'stale'.

I would suggest storing only the link identifiers (not the link elements themselves) as strings and then search for them each time the page has loaded.

Upvotes: 2

Related Questions