Cypress uses the cy.iframe()
command to locate elements within an iframe. This command allows Cypress to switch its focus to the desired iframe, then use regular Cypress commands like cy.get()
to locate elements within the iframe. Cypress does not treat elements within iframes any differently than elements outside of iframes; once the iframe is selected, Cypress can interact with elements inside it just like it would with any other element on the page.
How to work with iframes in Cypress tests using custom commands?
To work with iframes in Cypress tests using custom commands, you can create a custom command to interact with the iframes. Here's an example of how you can do this:
- Create a new Cypress command in your support/commands.js file:
1 2 3 4 5 6 7 8 9 10 11 12 |
Cypress.Commands.add('iframe', { prevSubject: 'element' }, ($iframe) => { return new Cypress.Promise(resolve => { const onIframeReady = () => { const contentWindow = $iframe.prop('contentWindow') resolve(contentWindow) } $iframe.on('load', onIframeReady) if ($iframe.prop('complete')) { onIframeReady() } }) }) |
- In your test file, use the custom command to interact with the iframe. For example, you can switch to the iframe, perform some actions inside the iframe, and then switch back to the main window:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
describe('iframe test', () => { it('should interact with iframe', () => { cy.visit('https://example.com') cy.get('iframe').iframe().then(iframe => { const body = iframe.document.querySelector('body') cy.wrap(body).find('input').type('Hello, World!') }) // switch back to the main window cy.get('body').type('{esc}') }) }) |
With this custom command, you can easily interact with iframes in your Cypress tests without having to manually handle switching to and from the iframes each time.
How to switch back to the main window after interacting with an iframe using Cypress?
You can switch back to the main window after interacting with an iframe in Cypress using the cy.switchTo()
command. Here's an example:
1 2 3 4 5 6 7 8 |
// interacting with the iframe cy.get('iframe').then(($iframe) => { const $body = $iframe.contents().find('body'); cy.wrap($body).find('.element-in-iframe').click(); }); // switching back to the main window cy.switchTo('window'); |
In this example, we first interact with the elements inside the iframe using the standard Cypress commands. Then, we use the cy.switchTo('window')
command to switch back to the main window. This command is specifically designed to switch between frames and windows in Cypress.
What is the purpose of using iframes on a webpage?
The purpose of using iframes on a webpage is to embed or display content from another source within the primary webpage. This allows for the integration of external content, such as videos, maps, or social media feeds, without redirecting the user to a different website. iframes are commonly used to streamline the user experience and enhance the functionality of a webpage.