user3561614
user3561614

Reputation: 1094

How to fix unknown error: unhandled inspector error: "Cannot find context with specified id"

The following code throws occasionally an org.openqa.selenium.WebDriverException.

WebElement element = driver.findElement(by);
element.click();
(new WebDriverWait(driver, 4, 100)).until(ExpectedConditions.stalenessOf(element));

The page looks like this (by is a selector for <a></a>)

<iframe name="name">
  <html id="frame">
    <head>
      ...
    </head>
    <body class="frameA">
      <table class="table">
        <tbody>
          <tr>
            <td id="83">
              <a></a>
            </td>
          </tr>
        </tbody>
      </table>
    </body>
  </html>
</iframe>

The message is unknown error: unhandled inspector error: {"code":-32000,"message":"Cannot find context with specified id"}. element is part of an iframe and the click can cause the content of the iframe to reload. The exception is thrown while waiting. What does this exception mean and how could I fix it?

Upvotes: 3

Views: 5374

Answers (1)

undetected Selenium
undetected Selenium

Reputation: 193338

This error message...

unknown error: unhandled inspector error: {"code":-32000,"message":"Cannot find context with specified id"}

...implies that the WebDriver instance was unable to locate the desired element.

As you mentioned in your question that the element is part of an <iframe> and invoking click() can cause the content of the iframe to reload in that case you need to traverse back to the defaultContent and again switch back again to the desired iframe with WebDriverWait and then induce WebDriverWait either for stalenessOf() previous element or presence of next desired element as follows :

WebElement element = driver.findElement(by);
element.click();
driver.switchTo().defaultContent(); // or driver.switchTo().parentFrame();
new WebDriverWait(driver, 10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.name("xyz")));
// wait for stalenessOf previous element (visibility of next desired element preferred)
new WebDriverWait(driver, 4, 100).until(ExpectedConditions.stalenessOf(element));
// or wait for visibility of next desired element (preferred approach)
new WebDriverWait(driver, 4, 100).until(ExpectedConditions.visibilityOfElementLocated(next_desired_element));

Upvotes: 3

Related Questions