0
0
Cypresstesting~5 mins

Iframe interaction strategies in Cypress

Choose your learning style9 modes available
Introduction

Sometimes web pages show content inside a small window called an iframe. We need special ways to test and interact with these iframes because they act like separate pages inside the main page.

When you want to click a button inside an iframe on a webpage.
When you need to check text or data shown inside an iframe.
When filling out a form that is inside an iframe.
When verifying that an iframe loads the correct content.
When testing a widget or ad that appears inside an iframe.
Syntax
Cypress
cy.get('iframe').its('0.contentDocument.body').should('not.be.empty').then(cy.wrap)

This code gets the iframe element, accesses its document body, and wraps it so you can use Cypress commands inside the iframe.

Always wait for the iframe content to load before interacting.

Examples
Finds the iframe with id 'myFrame', waits for its body to load, then clicks a button inside it.
Cypress
cy.get('iframe#myFrame').its('0.contentDocument.body').should('not.be.empty').then(cy.wrap).find('button').click()
Types an email into an input field inside the iframe.
Cypress
cy.get('iframe').its('0.contentDocument.body').should('not.be.empty').then(cy.wrap).find('input[name="email"]').type('test@example.com')
Checks that the text 'Welcome' is visible inside the iframe.
Cypress
cy.get('iframe').its('0.contentDocument.body').should('not.be.empty').then(cy.wrap).contains('Welcome').should('be.visible')
Sample Program

This test visits a page with an iframe, finds the iframe by id 'loginFrame', waits for it to load, clicks the submit button inside it, and then checks the main page for a success message.

Cypress
describe('Iframe interaction test', () => {
  it('Clicks a button inside iframe', () => {
    cy.visit('https://example.com/page-with-iframe')
    cy.get('iframe#loginFrame').its('0.contentDocument.body').should('not.be.empty').then(cy.wrap)
      .find('button#submit').click()
    cy.get('#result').should('contain.text', 'Success')
  })
})
OutputSuccess
Important Notes

Always ensure the iframe is fully loaded before interacting to avoid flaky tests.

Use unique and stable selectors for iframes and elements inside them.

Remember that cross-origin iframes may block access due to browser security.

Summary

Iframes need special handling because they are like separate pages inside a page.

Use cy.get('iframe').its('0.contentDocument.body').then(cy.wrap) to work inside iframes.

Wait for iframe content to load before interacting to keep tests stable.