Accessing iFrame elements using Nightwatch

Simon Legg picture Simon Legg · Dec 16, 2015 · Viewed 8.5k times · Source

I am using Nightwatch to test that the correct value has been given to a div within an iframe.

My html;

<div class="o-ads__inner" id="leaderboard-gpt">
  <div id="google_ads_iframe">
    <iframe id="some_id">
      #document
        <html>
          <head></head>
          <body>
            <div id="ad-data" creative-id="53134803289">
              <!-- All of the stuff -->
            </div>
          </body>
        </html>
    </iframe>
  </div>
  <iframe><!-- Another iframe (I don't want) --></iframe>
</div>

This is my nightwatch test;

module.exports = {
  'Leaderboard Visibility' : function (client) {
    client
    .url(some_url)
    .waitForElementVisible('body', 5000)
    .waitForElementPresent('#leaderboard > iframe', 10000)
    .pause(5000)
    .frame(0)
      .pause(5000)
      .waitForElementPresent('div#ad-data', 5000)
      .assert.attributeContains('div#ad-data', 'creative-id', '53134803289')
    .end();
  }
};

The error I get from Nightwatch is Timed out while waiting for element <div#ad-data> to be present for 5000 milliseconds. I know that it is there by checking before the failing line.

I have put in the 2 .pause(5000)s as similar questions suggest it may be a problem that the contents in the iframe isn't loading quickly enough. I don't think that's the case here due to some debugging I have done but I have left them there for the time being.

I'm thinking that I can't access the div#ad-data because the iframe has it's own contentDocument property, which contains the head & body (and thus subsequent divs).

How can I assert the value of the div's property within the iframe's contentDocument using Nightwatch?

Answer

Killuminati picture Killuminati · Dec 24, 2015

for your first iframe <iframe id="some_id"> use .frame('some_id').