Cypress Iframe Not Loading Fix
In this tutorial, you'll learn about Cypress Iframe Not Loading Fix. We cover key concepts, practical examples, and best practices.
Cypress can't find elements inside an iframe — cy.get() doesn't work across iframe boundaries.
The Problem
// WRONG — Cypress can't find elements inside iframes
cy.visit('/');
cy.get('#my-iframe').within(() => {
cy.get('button').click(); // Fails — can't find button inside iframe
});
Cypress commands operate on the top-level document by default. Elements inside iframes are in a separate document and require special handling.
Step-by-Step Fix
1. Create a custom iframe command
// RIGHT — custom iframe command
Cypress.Commands.add('iframe', (selector) => {
return cy.get(selector)
.its('0.contentDocument.body')
.should('be.visible')
.then(cy.wrap);
});
cy.visit('/');
cy.iframe('#my-iframe').within(() => {
cy.contains('button', 'Submit').click();
});
2. Use cy.iframe plugin
// Install: npm install -D cypress-iframe
import 'cypress-iframe';
cy.visit('/');
cy.frameLoaded('#my-iframe');
cy.iframe('#my-iframe').find('button').click();
3. Handle cross-origin iframes
// RIGHT — cross-origin iframe handling
cy.visit('/');
cy.get('#external-iframe').then(($iframe) => {
const content = $iframe.contents();
cy.wrap(content.find('button')).should('be.visible').click();
});
4. Wait for iframe to load
// RIGHT — wait for iframe content
cy.get('#my-iframe').then(($iframe) => {
const $body = $iframe.contents().find('body');
// Wait for iframe to fully load
cy.wrap($body).find('[data-testid="loaded"]').should('be.visible');
});
Expected output:
✓ interacts with iframe content
✓ uses iframe plugin
✓ waits for iframe to load
Prevention Tips
- Use custom commands or plugins for iframe interaction
- Wait for iframe content to load before interacting
- Handle cross-origin iframes with
cy.origin()if needed - Use
.within()on iframe content wrapped withcy.wrap() - Test iframe loading state and error scenarios
Common Mistakes with iframe
- Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
These mistakes appear frequently in real-world CYPRESS code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro