'WebDriverException: target frame detached while interacting with elements within iframe using ChromeDriver Chrome and Selenium

I use Chromedriver 78.0.3904.70,

WebDriverException: target frame detached exception 

has occurred, but in previous version of chromedriver all worked fine. Now in my iFrame I can't find any elements during the autotest, where should be another iFrame, but i can do it by hand. Also switching to iFrame doing successfully during autotest. I think may be there is a bug in new chromedriver? Any ideas?

org.openqa.selenium.WebDriverException: target frame detached
  (Session info: chrome=78.0.3904.97)
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: 'PDF323-440G4', ip: '172.16.14.147', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_181'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 78.0.3904.97, chrome: {chromedriverVersion: 78.0.3904.70 (edb9c9f3de024..., userDataDir: C:\Users\Nikolay\AppData\Lo...}, goog:chromeOptions: {debuggerAddress: localhost:64307}, javascriptEnabled: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: XP, platformName: XP, proxy: Proxy(), setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify}
Session ID: c6f28448e742438746371ee017a51dda


Solution 1:[1]

As a workaround, we can use a try and catch block for the elements in which this error occurs - and the tests will continue further without stopping

try {

button.click();

} catch (WebDriverException e) {

e.printStackTrace();

}

Solution 2:[2]

This error message...

WebDriverException: target frame detached

...implies that for a certain HttpRequest the resultant HttpServerResponseInfo was net::HTTP_NOT_FOUND.


Details

As per the discussion Some error codes are not standard compliant there were some error codes returned by the ChromeDriver which were not compliant to the W3C standard. They were replaced with the corresponding standard error codes:

  • asynchronous script timeout -> script timeout
  • element not visible -> element not interactable
  • no such session -> invalid session id
  • session not created exception -> session not created
  • xpath lookup error -> invalid selector

Additionally, there are some Chrome-specific error codes which still exists and most clients will treat them as unknown error. These error codes are:

  • chrome not reachable
  • disconnected
  • forbidden
  • no such execution context
  • tab crashed
  • target frame detached

This issue was addressed through the bug / commit and the current status is ToBeReleased.


Deep Dive

The error target frame detached is the outcome of case kTargetDetached where case kTargetDetached is defined in http_handler.cc and occurs when the HttpServerResponseInfo contains HTTP_NOT_FOUND as follows:

void HttpHandler::HandleCommand(
    const net::HttpServerRequestInfo& request,
    const std::string& trimmed_path,
    const HttpResponseSenderFunc& send_response_func) {
  base::DictionaryValue params;
  std::string session_id;
  CommandMap::const_iterator iter = command_map_->begin();
  while (true) {
    if (iter == command_map_->end()) {
      if (w3cMode(session_id, session_thread_map_)) {
    PrepareResponse(
        trimmed_path, send_response_func,
        Status(kUnknownCommand, "unknown command: " + trimmed_path),
        nullptr, session_id, true);
      } else {
    std::unique_ptr<net::HttpServerResponseInfo> response(
        new net::HttpServerResponseInfo(net::HTTP_NOT_FOUND));
    response->SetBody("unknown command: " + trimmed_path, "text/plain");
    send_response_func.Run(std::move(response));
      }
      return;
    }
    if (internal::MatchesCommand(
        request.method, trimmed_path, *iter, &session_id, &params)) {
      break;
    }
    ++iter;
  }

and most possibly the reason in your case is kTargetDetached:

case kTargetDetached:
  response.reset(new net::HttpServerResponseInfo(net::HTTP_NOT_FOUND));
  break;

Solution 3:[3]

I was also facing the same issue on Version 79. Updated to chrome Version 80.0.3987.53 (Official Build) beta (64-bit) on my mac machine and used chromedriver version 80.0.3987.16 while working with selenium. Switching to iframe is working fine now.

enter image description here

Got a hint from the above point that it has been fixed in version 80. Hope it helps!

Solution 4:[4]

May not be correct or optimal solution but after adding Thread.sleep and nested try catch block issue got resolved. Note: in WebDriverException I tried the same element again

    try
    {
    Thread.sleep(1000);
    yourWebelement.click();
    }
    catch(WebDriverException e)
    {
        yourWebelement.click();
    }
    catch(Exception ee)
    {
        ee.printStackTrace();
        throw ee;
    }

Solution 5:[5]

Retrying and switching frame worked for me:

public void retryForDetachedFrame(final WebDriver driver, final String elementXpath, final int frameId) throws Exception {
    int webDriverExceptionCounter = 0;
    while (webDriverExceptionCounter < 5) {
        try {
            driver.findElement(By.xpath(elementXpath));
            break;
        } catch (final WebDriverException ex) {
            webDriverExceptionCounter++;
            if (webDriverExceptionCounter == 5) {
                log.error("WebDriverException, not trying again: {}", webDriverExceptionCounter);
                throw ex;
            } else {
                log.info("WebDriverException, retrying: {}", webDriverExceptionCounter);
                Thread.sleep(500);
                final WebDriverWait wait = new WebDriverWait(driver, 15);
                wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(frameId));
            }
        } catch (final Exception e) {
            log.error("Exception: {}", e.getClass());
            throw e;
        }
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 vladys2019
Solution 2 undetected Selenium
Solution 3 learner
Solution 4 Ritesh
Solution 5 Atul Kulkarni