How to interact with elements within an iframe in Cypress?
In Cypress, you can interact with elements within an iframe by switching to that frame first before interacting with the element. Here is an example of how you can click on the “Login” button within an iframe using the “google-auth-library” id:
cy.get('iframe[name="google-auth-library"]')
.its('0.contentDocument.body')
.find('#login-button')
.click()
This code first selects the iframe using its name attribute, then accesses the document’s body and finds the element with the id “login-button” and finally clicks on it. You could also just use the id of the iframe if it is available.
cy.get('#google-auth-library')
.its('contentDocument.body')
.find('#login-button')
.click()
You can also use the cy.iframe()
command to switch focus to the iframe and then interact with the element as normal.
cy.iframe('#google-auth-library')
.find('#login-button')
.click()
Wrap method in Cypress:
In Cypress, you can interact with elements within an iframe by switching to that frame first before interacting with the element. There are a few different ways to do this:
.its()
method: You can use the.its()
method to access the iframe’s contentDocument and then interact with elements within that document. For example:
cy.get('iframe[name="my-iframe"]')
.its('0.contentDocument.body')
.find('#element-id')
.click()
.then()
method: You can use the.then()
method to access the iframe’s contentDocument and then interact with elements within that document. For example:
cy.get('iframe[name="my-iframe"]')
.then(iframe => {
const body = iframe.contents().find('body')
cy.wrap(body).find('#element-id').click()
})
cy.iframe()
command: You can use thecy.iframe()
command to switch focus to the iframe and then interact with the element as normal. For example:
cy.iframe('#my-iframe')
.find('#element-id')
.click()
It’s worth noting that Cypress will automatically retry the action on the element if it is not immediately available and also you can use the iframe element id or the name of the iframe in the above examples.
For more blogs, Click here
Author : Ghulam Nabi
Leave a comment