Stale element reference: element is not attached to the page document.

Not a way to solve it, it happens intermittently, please help me.

04-03-2018 10:21:14 AM - [ERROR] - stale element reference: element is not attached to the page document

(Session info: chrome=65.0.3325.181)

(Driver info: chromedriver=2.35.528161 (5b82f2d2aae0ca24b877009200ced9065a772e73),platform=Windows NT 10.0.16299 x86_64) (WARNING: The server did not provide any stacktrace information)

Command duration or timeout: 0 milliseconds

For documentation on this error, please visit: Selenium

Build info: version: ‘3.7.1’, revision: ‘8a0099a’, time: ‘2017-11-06T21:07:36.161Z’

System info: host: ‘NOT-104’, ip: ‘192.168.0.139’, os.name: ‘Windows 10’, os.arch: ‘amd64’, os.version: ‘10.0’, java.version: ‘1.8.0_102’

Driver info: com.kms.katalon.selenium.driver.CChromeDriver

Capabilities {acceptInsecureCerts: false, acceptSslCerts: false, applicationCacheEnabled: false, browserConnectionEnabled: false, browserName: chrome, chrome: {chromedriverVersion: 2.35.528161 (5b82f2d2aae0ca…, userDataDir: C:\Users\gcesario\AppData\L…}, cssSelectorsEnabled: true, databaseEnabled: false, handlesAlerts: true, hasTouchScreen: false, javascriptEnabled: true, locationContextEnabled: true, mobileEmulationEnabled: false, nativeEvents: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: XP, platformName: XP, rotatable: false, setWindowRect: true, takesHeapSnapshot: true, takesScreenshot: true, unexpectedAlertBehaviour: , unhandledPromptBehavior: , version: 65.0.3325.181, webStorageEnabled: true}

Session ID: 5fb2aedc6fa347f6f399e459c1daf4dc

04-03-2018 10:21:14 AM - [ERROR] - Test Cases/Recebimento FAILED because (of) org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document

(Session info: chrome=65.0.3325.181)

(Driver info: chromedriver=2.35.528161 (5b82f2d2aae0ca24b877009200ced9065a772e73),platform=Windows NT 10.0.16299 x86_64) (WARNING: The server did not provide any stacktrace information)

Command duration or timeout: 0 milliseconds

For documentation on this error, please visit: Selenium

Build info: version: ‘3.7.1’, revision: ‘8a0099a’, time: ‘2017-11-06T21:07:36.161Z’

System info: host: ‘NOT-104’, ip: ‘192.168.0.139’, os.name: ‘Windows 10’, os.arch: ‘amd64’, os.version: ‘10.0’, java.version: ‘1.8.0_102’

Driver info: com.kms.katalon.selenium.driver.CChromeDriver

Capabilities {acceptInsecureCerts: false, acceptSslCerts: false, applicationCacheEnabled: false, browserConnectionEnabled: false, browserName: chrome, chrome: {chromedriverVersion: 2.35.528161 (5b82f2d2aae0ca…, userDataDir: C:\Users\gcesario\AppData\L…}, cssSelectorsEnabled: true, databaseEnabled: false, handlesAlerts: true, hasTouchScreen: false, javascriptEnabled: true, locationContextEnabled: true, mobileEmulationEnabled: false, nativeEvents: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: XP, platformName: XP, rotatable: false, setWindowRect: true, takesHeapSnapshot: true, takesScreenshot: true, unexpectedAlertBehaviour: , unhandledPromptBehavior: , version: 65.0.3325.181, webStorageEnabled: true}

Session ID: 5fb2aedc6fa347f6f399e459c1daf4dc

Hi Gabriel

It would be nice to see the lines of code that caused the error.

If you believe that the object should be ready to interact with and sometimes this same test passes, then it is likely one of two things:

1 - The network/server is running slower than usual.

Perhaps you didn’t refresh the object being tested after the page
updated (possibly via ajax?) or you didn’t wait long enough for it to be
loaded/visible or otherwise addressable.

2 - WebDriver is lying to you.

This is a rare occurrence but happens often enough to cause you pain. There is a bug (certainly in the gecko driver) that causes that message to appear when it should not. The cause is a mystery. The cure is to avoid using WebUI.waitFor* and WebUI.click etc and write your own using JavaScript which allows you to deal more directly with the page. (Warning: This is not a trivial undertaking!)

Russ

Russ, this is a line of code:
CustomKeywords.‘newpackage.newkeyword.clickUsingJS’(findTestObject(‘Page_GTI PLUG/span_Adicionar Produto’), 30)

I am using a JS command in Keyword to replace the click, but it does not always work, it follows below:

public class newkeyword {

@Keyword

def clickUsingJS(TestObject to, int timeout)

{

WebDriver driver = DriverFactory.getWebDriver()

WebElement element = WebUiCommonHelper.findWebElement(to, timeout)

JavascriptExecutor executor = ((driver) as JavascriptExecutor)

executor.executeScript(‘arguments[0].click()’, element)

}

}

Are you waiting until that TO is visible before you call clickUsingJS?

Yes, other buttons work with JS.

Okay, let’s try this…

Firstly, does your element have an ID? It will just make this easier, if it does.

If not, just replace my-button with your ID:

def clickUsingJS2(String selector) {
  WebUI.executeJavaScript('document.querySelector("' + selector + '").click()', null)
}

And call it like so:

clickUsingJS2("#my-button")

if you have jQuery on the page (and you KNOW it’s “ready” to work with) you can do this:

def clickUsingJQ(String selector) {
  WebUI.executeJavaScript('$("' + selector + '").click()', null)
}

And call it just like before.

Sorry Russ, I’m just inexperienced in all of this.
Where can I put this code?
Is not it the same as I do not put any place on my button?
Thank you!

Put it right next to your Keyword code. Or, you can create another Keyword file/package if you wish, but the same file would make sense, I guess.

If you make those two methods static (I forgot to add that) then you don’t need to say @Keyword above them… unless you want them to appear in the Keyword dropdown in manual view (I never use that dropdown so I always remove @Keyword).

So make them look like this:

static void clickUsingJS2(String selector) {
  WebUI.executeJavaScript('document.querySelector("' + selector + '").click()', null)
}

If you need to return something from one of these methods, it’s probably best to “cast” the returned result accordingly. This example returns a String:

/**
  * Call somethingInteresting via javascript and querySelector.
  * @param selector (String) a CSS selector
  * @return String
 */
static String somethingUsingJS2(String selector) {
  return (String) WebUI.executeJavaScript('return document.querySelector("' + selector + '").doSomethingInteresting()', null)
}

Notice there are two return statements: one in Groovy code and one inside the javascript string. You can call it like this:

String x = somethingUsingJS2("#my-id")

Or…

WebUI.comment('Something interesting ' + somethingUsingJS2("#my-id"))

Hi, I am trying to click on an element using LinkText.
Eg: myelement = driver.FindElement(By.LinkText(StoreFile)) 'Click on report by name

                logger.Debug("Report Found as " & myelement.Text)

                If myelement Is Nothing Then

                    GoTo endTry

                Else

                    myelement.Click()

                    logger.Debug("Report clicked is " & StoreFile)

                End If  

But, I get the following error:

The Error Is OpenQA.Selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document

(Session info: chrome=66.0.3359.139)

(Driver info: chromedriver=2.35.528161 (5b82f2d2aae0ca24b877009200ced9065a772e73),platform=Windows NT 6.1.7601 SP1 x86_64)

at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)

at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)

at OpenQA.Selenium.Remote.RemoteWebElement.Click()

at ExcelAddIn1.Ribbon1.BrandReview(String ReadFile).

Is there a reason as to why it can’t find the element using the LinkText even though the element is visible on the web page? Is there a solution to resolve this, please?

These articles describe this issue.

http://www.sahajamit.com/post/mystery-of-stale-element-reference-exception/

I have no solution for Katalon Studio yet.

Has anyone found an answer for this that works? I’m trying the script as provided and not having any luck. We had to wrap SE code in C# here and used a try, catch combo. Is there anything like that to get past this. It’s making Katalon virtually unusable for me as it’s happening on pages that should take about 5 minutes to script. Thanks.

1 Like

I have uncovered two general principles when interacting with web pages through Katalon:

  1. Sometimes it is necessary to interact with elements through javascript
  2. Waiting won’t always resolve the issue. Retry clicking or inserting data even after waiting…

Case in point, I have pasted code below that will open www.katalon.com, log in, and perform a keyword search. After trial and error I found that by using a combination of javascript, and waiting and repeating steps as was able to accomplish this task:

//open browser

WebUI.openBrowser(“www.katalon.com”)

//click on login button to login

WebUI.click(findTestObject(‘Object Repository/Script/Page_Katalon Studio Best automated/a_Sign in’))

//enter username and password

WebUI.setText(findTestObject(‘Object Repository/Script/Page_Sign in Katalon Studio/input_user_email’), "xxxxx@xxxxx.com")

WebUI.setText(findTestObject(‘Object Repository/Script/Page_Sign in Katalon Studio/input_user_pass’), “xxxxxx” )

//click on sign in

WebUI.click(findTestObject(‘Object Repository/Script/Page_Sign in Katalon Studio/input_login-btn’))

//click on search

WebUI.click(findTestObject(‘Object Repository/Script/Page_Katalon Studio Free Download/img’))
//enter “script” in search field

WebUI.executeJavaScript(“document.getElementById(‘input_text_search’).value=‘script’;”, null)
//wait for search icon to become available and then click on search icon to perfom search

WebUI.waitForElementClickable(findTestObject(‘Object Repository/New Test Case/Page_Katalon Studio Free Download/img’), 50)

//repeat previous step but without waiting

WebUI.click(findTestObject(‘Object Repository/New Test Case/Page_Katalon Studio Free Download/img’))
//reenter “script” into search field

WebUI.executeJavaScript(“document.getElementById(‘input_text_search’).value=‘script’;”, null)
//reclick seach icon

WebUI.click(findTestObject(‘Object Repository/New Test Case/Page_Katalon Studio Free Download/img’))

Julie Mortlock said:

Has anyone found an answer for this that works? I’m trying the script as provided and not having any luck. We had to wrap SE code in C# here and used a try, catch combo. Is there anything like that to get past this. It’s making Katalon virtually unusable for me as it’s happening on pages that should take about 5 minutes to script. Thanks.

I’m in the same boat here. Anyone have any updates on this?

1 Like

I am in the same boat. I can sometimes avoid the error by adding delays to the test steps but then it causes the test execution to take ridiculously long.

For me the thing which resolve the issue was to change locator to CssSelector instead of Xpath. Now, I don’t even need to use any kind of wait method or (what worse any delays) before clicking in that element - no more stale element reference exception…I spend several hours to figure out what is wrong with this click action, and that was simply xpath which does not work perfectly in DOM (seems to)

Hi,

Since it is hidden element or element not attached to the DOM, Javascript executor to be used to scroll to the element and click.

def scrolldown(){
	JavascriptExecutor executor = ((JavascriptExecutor) DriverFactory.getWebDriver())
	executor.executeScript("window.scrollBy(0,4000)")
}

def clickUsingJS2(String selector) {
WebUI.executeJavaScript(‘document.querySelector("’ + selector + ‘").click()’, null)
}
i user this one,executeJavaScript doesn’t work even i user ctrl + shift +o

Hi @1018742342

What do you mean it doesn’t work ? Is there any error ?

it’s works after i manual add import com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords as WebUI in keyword section,ctrl + shift +o doesn’t automatic filled this import statements

there others question
Caused by: com.kms.katalon.core.exception.StepFailedException: Actual text ‘aliceapprover3 hpapprover3’ and expected text ‘aliceapprover3 hpapprover3’ of test object ‘Object Repository/Primary_Approver_name’ are NOT matched.
at com.kms.katalon.core.webui.keyword.internal.WebUIKeywordMain.stepFailed(WebUIKeywordMain.groovy:64)
at com.kms.katalon.core.webui.keyword.builtin.VerifyElementTextKeyword$_verifyElementText_closure1.doCall(VerifyElementTextKeyword.groovy:57)
at com.kms.katalon.core.webui.keyword.builtin.VerifyElementTextKeyword$_verifyElementText_closure1.call(VerifyElementTextKeyword.groovy)
at com.kms.katalon.core.webui.keyword.internal.WebUIKeywordMain.runKeyword(WebUIKeywordMain.groovy:20)
… 84 more

I think they are matched why failed

I get this error, anyone can help me? thank you
Reason:

org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document

(Session info: chrome=78.0.3904.108)

For documentation on this error, please visit: https://www.seleniumhq.org/exceptions/stale_element_reference.html

Build info: version: ‘3.141.59’, revision: ‘e82be7d358’, time: ‘2018-11-14T08:25:53’

System info: host: ‘Januaris-MacBook-Pro.local’, ip: ‘fe80:0:0:0:1cc2:8628:310f:9668%en0’, os.name: ‘Mac OS X’, os.arch: ‘x86_64’, os.version: ‘10.14.6’, java.version: ‘1.8.0_181’

Driver info: com.kms.katalon.core.webui.driver.ExistingRemoteWebDriver

Capabilities {javascriptEnabled: true, platform: ANY, platformName: ANY}

Session ID: 2d2d9e6cb678a9034f0f4191d87678bf

*** Element info: {Using=tag name, value=td}

at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:187)

at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:122)

at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:49)

at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158)

at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552)

at com.kms.katalon.core.webui.driver.ExistingRemoteWebDriver.execute(ExistingRemoteWebDriver.java:108)

at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:285)

at org.openqa.selenium.remote.RemoteWebElement.findElements(RemoteWebElement.java:204)

at org.openqa.selenium.remote.RemoteWebElement.findElementsByTagName(RemoteWebElement.java:281)

at org.openqa.selenium.By$ByTagName.findElements(By.java:312)

at org.openqa.selenium.remote.RemoteWebElement.findElements(RemoteWebElement.java:177)

at org.openqa.selenium.WebElement$findElements.call(Unknown Source)

at C271_Brand is able to sign in from admin dashboard.run(C271_Brand is able to sign in from admin dashboard:65)

at com.kms.katalon.core.main.ScriptEngine.run(ScriptEngine.java:194)

at com.kms.katalon.core.main.ScriptEngine.runScriptAsRawText(ScriptEngine.java:119)

at com.kms.katalon.core.main.TestCaseExecutor.runScript(TestCaseExecutor.java:337)

at com.kms.katalon.core.main.TestCaseExecutor.doExecute(TestCaseExecutor.java:328)

at com.kms.katalon.core.main.TestCaseExecutor.processExecutionPhase(TestCaseExecutor.java:307)

at com.kms.katalon.core.main.TestCaseExecutor.accessMainPhase(TestCaseExecutor.java:299)

at com.kms.katalon.core.main.TestCaseExecutor.execute(TestCaseExecutor.java:233)

at com.kms.katalon.core.main.TestCaseMain.runTestCase(TestCaseMain.java:114)

at com.kms.katalon.core.main.TestCaseMain.runTestCase(TestCaseMain.java:105)

at com.kms.katalon.core.main.TestCaseMain$runTestCase$0.call(Unknown Source)

at TempTestCase1575440381780.run(TempTestCase1575440381780.groovy:21)