Sign Up

Sign In

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

You must login to ask question.

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Interact with elements within an iframe in Cypress

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:

  1. .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()
  1. .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()
})
  1. cy.iframe() command: You can use the cy.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

Related Posts

Cypress to perform a file upload

Cannot find name 'Cypress'

Draw a line using Cypress

Parallelizing Cypress with Jenkins

Leave a comment

You must login to add a new comment.