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.
Iframe interaction strategies in 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.
cy.get('iframe#myFrame').its('0.contentDocument.body').should('not.be.empty').then(cy.wrap).find('button').click()
cy.get('iframe').its('0.contentDocument.body').should('not.be.empty').then(cy.wrap).find('input[name="email"]').type('test@example.com')
cy.get('iframe').its('0.contentDocument.body').should('not.be.empty').then(cy.wrap).contains('Welcome').should('be.visible')
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.
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') }) })
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.
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.