I would like to thank the stackoverflow community for all the help. I have been recently trying to handle “StaleElementReferenceException”, but can’t find one solution that fits all. Many members of the stackoverflow community suggested using following code for StaleElementReferenceException. Please click here for more details on the code. This code sometimes works but not all the time for my applications.
So I took one more approach wait for dom to load. However, that didn’t solve the problem either. So I had to hack in my code to make it work, but I know this is not the best way of solving the problem and my code has many flaws. If someone can help me solve StaleElementReferenceException and page load problem.
Check for page load code
public void pReady() {
JavascriptExecutor js = (JavascriptExecutor)driver;
//Initially bellow given if condition will check ready state of page.
if (js.executeScript("return document.readyState").toString().equals("complete")){
System.out.println("Page Is loaded.");
return;
}
//This loop will rotate for 25 times to check If page Is ready after every 6 second.
//You can replace your value with 25 If you wants to Increase or decrease wait time.
for (int i=0; i<25; i++){
try {
Thread.sleep(6000);
}catch (InterruptedException e) {}
//To check page ready state.
if (js.executeScript("return document.readyState").toString ().equals("complete")){
break;
}
}
}
This didn't fix either as after DOM is load there seems to be some other jquery in background and page refresh few more times.
Please check my code
public void newpagebutton() {
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.elementToBeClickable(by.id("abc")));
try {
pReady();
} finally {
if (retryingFindClick(by.id("abc"))) {
log.info ("Submit For Request Completed.. Moving to Main Page");
} else{
Log.error("Submit For Request not enable");
return;
} try {
WebElement sub = driver.findElement(by.id("abc"));
while (sub.isDisplayed()) {
retryingFindClick(by.id("abc"));
}
} catch (StaleElementReferenceException e) {
}
wait.until(ExpectedConditions.invisibilityOfElementLocated(by.id("abc")));
}
}
Thank you in advance for your help!