title: GhostDriver throwing stale exception "Element does not exist in cache" when executing javascript on existing element
body: <hr>
  
  <p>Having problems with stale exception, GhostDriver is bubbling something was changed sice last execution.<br>
  On this {<a href="https://stackoverflow.com/questions/5709204/random-element-is-no-longer-attached-to-the-dom-staleelementreferenceexception">Random “Element is no longer attached to the DOM” StaleElementReferenceException</a>} question, that have more than 16k views, someone is telling about race conditions and things changing on test time but my code execute so fast that i cant believe something was changed.<br>
  Im changing nothing, all code execute fast, maybe the page itself is changing on the small time frame of test fragment execution.<br>
  The <code>myLibWorks.findElements(..</code> is ok and returning elements, its using <code>FluentWait&lt;SearchContext&gt;</code> then the element is available when method return.<br>
  It throws: </p>
  
  <blockquote>
    <p>Element does not exist in cache</p>
  </blockquote>
  
  <p>after when i try execute javascript on element.<br>
  Here is the simplified fragment of my Java code:  </p>
  
  <pre><code>by = getBy_A001();  
  List&lt;WebElement&gt; welCollecN1 = myLibWorks.findElements(driver, timeOutInSeconds, pollingForSecond, by);  
  if (welCollecN1 != null) {  
      WebElement wel01 = welCollecN1.iterator().next();  
      if(wel01 != null)  
      {  
          by = getBy_A002();  
          List&lt;WebElement&gt; welCollecN2 = myLibWorks.findElements(wel01, timeOutInSeconds, pollingForSecond, by);  
          if (welCollecN2 != null) {  
              WebElement wel02 = welCollecN2.iterator().next();  
              if(wel02 != null)  
              {  
                  String value = null;  
                  value = elm.getText();  
                  if(value.length() == 0) {  
                      //-------------------------------------------------  
                      // REACH here then i think its ok above, this works almost of time too  
                      // THIS line throws "Element does not exist in cache"  
                      value = (String) ((JavascriptExecutor) driver).executeScript(driver, "return arguments[0].innerHTML", wel02);   // &lt;&lt;== ERROR  
                      //-------------------------------------------------  
                  }  
              }  
          }  
      }  
  }  
  </code></pre>
  
  <hr>
  
  <blockquote>
    <p>Element does not exist in cache   caused by Request =>
    {"headers":{"Accept":"application/json,
    image/png","Connection":"Keep-Alive","Content-Length":"84","Content-Type":"application/json;
    charset=utf-8","Host":"127.0.0.1:4444"},"httpVersion":"1.1","method":"POST","post":"{\"args\":[{\"ELEMENT\":\":wdc:1371656598440\"}],\"script\":\"return
    arguments[0].innerHTML\"}","url":"/execute","urlParsed":{"anchor":"","query":"","file":"execute","directory":"/","path":"/execute","relative":"/execute","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/execute","queryKey":{},"chunks":["execute"]},"urlOriginal":"/session/efc7cf60-d8f6-11e2-9f07-192e7e451712/execute"}
    Command duration or timeout: 736 milliseconds For documentation on
    this error, please visit:
    <a href="http://seleniumhq.org/exceptions/stale_element_reference.html" rel="nofollow noreferrer">http://seleniumhq.org/exceptions/stale_element_reference.html</a> Build
    info: version: '2.32.0', revision: '6c40c18', time: '2013-04-09
    17:22:56' System info: os.name: 'Linux', os.arch: 'i386', os.version:
    '3.8.0-19-generic', java.version: '1.7.0_21' Session ID:
    efc7cf60-d8f6-11e2-9f07-192e7e451712 Driver info:
    org.openqa.selenium.remote.RemoteWebDriver Capabilities
    [{platform=LINUX, acceptSslCerts=false, javascriptEnabled=true,
    browserName=phantomjs, rotatable=false, driverVersion=1.0.3,
    locationContextEnabled=false, version=1.9.0, cssSelectorsEnabled=true,
    databaseEnabled=false, handlesAlerts=false,
    browserConnectionEnabled=false, proxy={proxyType=direct},
    nativeEvents=true, webStorageEnabled=false, driverName=ghostdriver,
    applicationCacheEnabled=false, takesScreenshot=true}]} =======</p>
  </blockquote>
  
  <hr>
  
  <p>The error looks bubbling from here : <a href="https://code.google.com/p/phantomjs/source/browse/src/ghostdriver/third_party/webdriver-atoms/deps.js?r=78d90641df12d10b1f30b2bb4c08b92d6aff5f9b" rel="nofollow noreferrer">https://code.google.com/p/phantomjs/source/browse/src/ghostdriver/third_party/webdriver-atoms/deps.js?r=78d90641df12d10b1f30b2bb4c08b92d6aff5f9b</a>  </p>
  
  <pre><code>/**  
   * Retrieves an element from the cache. Will verify that the element is
   * still attached to the DOM before returning.
   * @param {string} key The element's key in the cache.
   * @param {Document=} opt_doc The document whose cache to retrieve the element
   *     from. Defaults to the current document.
   * @return {Element|Window} The cached element.
   */
  bot.inject.cache.getElement = function(key, opt_doc) {
    key = decodeURIComponent(key);
    var doc = opt_doc || document;
    var cache = bot.inject.cache.getCache_(doc);
    if (!goog.object.containsKey(cache, key)) {
      // Throw STALE_ELEMENT_REFERENCE instead of NO_SUCH_ELEMENT since the
      // key may have been defined by a prior document's cache.
      throw new bot.Error(bot.ErrorCode.STALE_ELEMENT_REFERENCE,
          'Element does not exist in cache');
    }
  
    var el = cache[key];
  
    // If this is a Window check if it's closed
    if (goog.object.containsKey(el, 'setInterval')) {
      if (el.closed) {
        delete cache[key];
        throw new bot.Error(bot.ErrorCode.NO_SUCH_WINDOW,
            'Window has been closed.');
      }
      return el;
    }
  
    // Make sure the element is still attached to the DOM before returning.
    var node = el;
    while (node) {
      if (node == doc.documentElement) {
        return el;
      }
      node = node.parentNode;
    }
    delete cache[key];
    throw new bot.Error(bot.ErrorCode.STALE_ELEMENT_REFERENCE,
        'Element is no longer attached to the DOM');
  };
  </code></pre>
  
  <hr>