How to Access Iframe Elements in Cypress with TypeScript
Access same-origin iframe elements in Cypress with TypeScript, handle cross-origin limits, and troubleshoot reliable iframe tests.

For a same-origin iframe, select the frame, wait for its document body to exist, and wrap that body with cy.wrap(). Cypress has no dedicated command that switches into an iframe; after wrapping the body, use normal Cypress queries and actions.
declare global {
namespace Cypress {
interface Chainable {
getIframeBody(selector: string): Chainable<JQuery<HTMLElement>>
}
}
}
Cypress.Commands.add('getIframeBody', (selector: string) => {
return cy
.get(selector)
.its('0.contentDocument.body')
.should('not.be.empty')
.then(cy.wrap)
})
// cypress/e2e/checkout.cy.ts
it('submits the payment form inside a same-origin iframe', () => {
cy.visit('/checkout')
cy.getIframeBody('#payment-frame').within(() => {
cy.get('[name="cardNumber"]').type('4242424242424242')
cy.get('[name="expiry"]').type('12/30')
cy.contains('button', 'Pay now').click()
})
})
The helper follows Cypress’s documented iframe pattern: cy.get() finds the frame, its('0.contentDocument.body') reads the first frame’s body, the assertion retries until content exists, and cy.wrap() returns the body to the Cypress command chain. See the Cypress command documentation and the official iframe example in Cypress’s TypeScript guidance.
How the access chain works
cy.get('#payment-frame')yields Cypress’s jQuery collection for the iframe element..its('0.contentDocument.body')reads the raw DOM body from the first matched iframe..should('not.be.empty')is retryable, so Cypress waits while the frame document is still loading..then(cy.wrap)wraps the body as a Cypress subject. Commands such asfind,contains,type, andclickcan now run inside it.
Use a specific iframe selector when a page contains multiple frames. Keep selectors inside the frame stable as well; the helper cannot compensate for selectors that change between builds.

Put the TypeScript helper in your Cypress support setup
Add the command to the support file loaded by your project, commonly cypress/support/e2e.ts. If your project uses a different support file, use that file instead.
// cypress/support/commands.ts
Cypress.Commands.add('getIframeBody', (selector: string) => {
return cy
.get(selector)
.its('0.contentDocument.body')
.should('not.be.empty')
.then(cy.wrap)
})
// cypress/support/e2e.ts
import './commands'
Declare the command type in a file included by tsconfig.json. A typical declaration is:
// cypress.d.ts
declare namespace Cypress {
interface Chainable {
getIframeBody(selector: string): Chainable<JQuery<HTMLElement>>
}
}
If TypeScript reports that getIframeBody does not exist, check that the declaration file is inside the configured include paths and restart the Cypress TypeScript process.
Using the wrapped iframe body
Query and assert
cy.getIframeBody('#profile-frame').within(() => {
cy.get('[data-testid="profile-name"]')
.should('be.visible')
.and('contain', 'Ada')
})
Find an element without within
cy.getIframeBody('#editor-frame')
.find('[contenteditable="true"]')
.click()
.type('Updated content')
Use a frame-specific alias
cy.getIframeBody('#settings-frame').as('settingsBody')
cy.get('@settingsBody')
.find('input[name="notifications"]')
.check()
Handle a frame that reloads
An iframe reload replaces its document. Acquire the body again after an action that causes navigation or reload instead of retaining a stale subject.
cy.getIframeBody('#wizard-frame').within(() => {
cy.contains('button', 'Next').click()
})
cy.getIframeBody('#wizard-frame')
.find('[data-step="2"]')
.should('be.visible')
Same-origin versus cross-origin iframes
The body-wrapping recipe works when the iframe document is same-origin with the page under test. Origin includes scheme, host, and port. For example, https://app.example.test and https://payments.example.test are different origins even though their registrable domain is the same.
For a cross-origin iframe, browser same-origin policy prevents the parent page from reading contentDocument. Cypress documents that the lookup can return null; the standard helper therefore cannot enter third-party payment forms, video embeds, or login widgets.
// Diagnostic check: useful for confirming that the body is unavailable.
cy.get('#third-party-frame')
.its('0.contentDocument')
.should('not.exist')
Do not use cy.origin() as an iframe switch. It runs commands after a test navigates the top-level window to another origin. Cypress explicitly excludes commands inside an embedded iframe from the supported cy.origin() scenario. Read the cy.origin documentation for the top-level navigation model.
What to do with a cross-origin embedded frame
Prefer an application-level seam
If the team controls the embedded application, expose a test-only integration seam, host a same-origin test fixture, or test the embedded application in its own Cypress project. These approaches preserve a browser security model that matches production.

Chromium-only security configuration
Cypress documents chromeWebSecurity: false as a possible workaround for cross-origin embedded frames in Chromium-family browsers:
// cypress.config.ts
import { defineConfig } from 'cypress'
export default defineConfig({
chromeWebSecurity: false,
})
This is not a general cross-browser solution. Cypress’s FAQ documents that the workaround is unsupported in Firefox and WebKit. Use it only when your CI browser matrix accepts that limitation, and verify the behavior on the exact Cypress and browser versions used by CI.
Top-level cross-origin navigation
When the test visits another origin as a top-level page, use cy.origin() for commands on that page:
cy.visit('/start')
cy.origin('https://accounts.example.test', () => {
cy.get('input[name="email"]').type('test@example.test')
cy.get('button[type="submit"]').click()
})
This example does not grant access to an iframe embedded in the original page.
Cypress 14 and document.domain
As of Cypress 14, Cypress no longer injects document.domain by default. Tests that navigate between different origins, including origins within one superdomain, must use cy.origin(). This change concerns top-level navigation and does not make cy.origin() capable of entering a cross-origin iframe.
injectDocumentDomain: true is documented as a transition option with compatibility caveats and deprecation. Check your installed Cypress version and current configuration before changing it.
Waiting for iframe content reliably
Do not add an arbitrary long sleep as the primary synchronization method. The non-empty body assertion retries while the iframe loads:
cy.get('#report-frame')
.its('0.contentDocument.body')
.should('not.be.empty')
.then(cy.wrap)
.find('[data-testid="report"]')
.should('be.visible')
When the application renders a known readiness marker, assert that marker as well:
cy.getIframeBody('#dashboard-frame').within(() => {
cy.get('[data-testid="dashboard-ready"]', { timeout: 15000 })
.should('exist')
})
Use a longer command timeout only for a known slow dependency. A timeout cannot solve a cross-origin restriction, an incorrect selector, or a frame that never receives its document.
Common errors and fixes
| Error or symptom | Likely cause | Fix |
|---|---|---|
contentDocument.body is null |
The frame is cross-origin, has not loaded, or the selector matched the wrong element. | Confirm scheme, host, and port; use a specific selector; wait for a non-empty body. A persistent null on a third-party frame is expected under same-origin policy. |
Timed out retrying its('0.contentDocument.body') |
The iframe did not load, the application blocked the request, or the frame selector is wrong. | Inspect the browser network and console logs, verify the frame URL, and assert a known readiness element. |
cy.origin() still cannot find iframe content |
cy.origin() handles top-level navigation, not embedded frames. |
Use the same-origin helper, an application seam, or the documented Chromium configuration workaround where appropriate. |
Command not found: getIframeBody |
The support file is not imported or the TypeScript declaration is outside the compiler include paths. | Import the commands file from the configured support entry point and include the declaration file in tsconfig.json. |
| Clicks affect the old page after a reload | The stored body subject belongs to a replaced document. | Call cy.getIframeBody() again after navigation or reload. |
| Element is covered or not actionable | A loading mask, consent UI, or animation remains inside the frame. | Wait for the frame’s ready marker, assert visibility, and use stable application state instead of forced clicks. |
| Works in Chrome but fails in Firefox or WebKit | chromeWebSecurity: false is Chromium-family specific. |
Remove the assumption of cross-origin iframe access and use a cross-browser-compatible test seam or separate test strategy. |
Performance and reliability practices
- Use one precise iframe selector instead of querying every iframe on the page.
- Wait on a meaningful readiness element after the body exists when the frame has multiple rendering phases.
- Keep frame interactions close to the command that acquires the body so reloads do not leave stale subjects.
- Stub slow, irrelevant network dependencies at the application boundary when the test does not need their behavior.
- Run cross-origin scenarios in the browser versions supported by your chosen Cypress configuration; do not assume a Chromium workaround represents Firefox or WebKit.
- Prefer deterministic test data and stable
data-testidselectors inside the frame.
Or skip the browser setup
If your goal is to capture a page or document rather than interact with controls inside an iframe, ScreenshotNeo provides a direct screenshot API and MCP server. It can remove cookie banners, newsletter popups, and chat widgets before capture; bot checks, blank pages, failed loads, timeouts, and cache hits are not billed; and its MCP server lets Claude, Cursor, and other MCP clients call take_screenshot, get_page_info, and capture_pdf.
See the ScreenshotNeo documentation for request options.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get(
"https://api.screenshotneo.com/v1/shot",
params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
timeout=90,
)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
The free plan includes 1,000 screenshots each month with no card. Paid plans start at $5 for 3,000 shots, and every feature is available on every plan. Create a free ScreenshotNeo account.
FAQ
Can Cypress access an iframe without a plugin?
Yes, when the iframe is same-origin. Read and wrap its document body, then use ordinary Cypress commands.
Why does Cypress return an empty body?
The frame may still be loading, the selector may be wrong, or the frame may be cross-origin. The non-empty assertion handles loading but cannot bypass browser origin security.
Is cy.origin() required for every different domain?
It is for top-level cross-origin navigation in current Cypress versions. It does not provide access to an embedded cross-origin iframe.
Can this helper work with multiple iframes?
Yes. Pass a selector for each frame and keep the selectors specific so the helper reads the intended frame.
Should I disable web security in CI?
Only if you accept the documented Chromium-family limitation and have confirmed the behavior in your supported browser matrix. It is not a Firefox or WebKit solution.


