0
votes

Basically I want to check if the element exists in the iframe. I am using cypress-iframe package for accessing elements in iframe. I searched a alot but I couldn't find any working answer. all the answers are about cypress itself but when it comes to iframe the solutions are not working. Example if the button exists in the iframe i want to click. If doesn't exist I want to continue with the other steps.

The error i get is cypress can't find the element. I tried with get function, it is the same. cypress tries to find the element and gives error because it doesn't find. But i want to know if exists and then take action.

cy.enter('.my-iframe').then(frameBody => {
  // This is not working
  if(frameBody().find(".my-button").length > 0){
    frameBody().find(".my-button").click();
  }  
});
<iframe class="my-iframe" src="content.html" style="height:200px;width:300px"></iframe>
2
Can you post a screenshot of the dom ? - Alapan Das
why you need a screenshot for that? Basically i need to check if a button is exists in iframe content. if exists I will click. I added the iframe. In the iframe there is no button with class ".my button". so I don't want cypress give me error. instead just continue with the other steps. - Hasip Timurtas

2 Answers

1
votes

Found the solution. Seems this is the only way to check if an element exists in the iframe with cypress.

With this solution we can check if the element doesn't exists then we can take another action or just continue with the next steps without any error.

cy.get(".my-iframe").then($frame => {
  const content = $frame.contents();
  if(content.find('.my-button').length){
    content.find('.my-button').click();
  }
});
0
votes

From the Cypress docs: (Cypress)

const getIframeDocument = () => {
  return cy
  .get('iframe[data-cy="the-frame"]')
  // Cypress yields jQuery element, which has the real
  // DOM element under property "0".
  // From the real DOM iframe element we can get
  // the "document" element, it is stored in "contentDocument" property
  // Cypress "its" command can access deep properties using dot notation
  // https://on.cypress.io/its
  .its('0.contentDocument').should('exist')
}

const getIframeBody = () => {
  // get the document
  return getIframeDocument()
  // automatically retries until body is loaded
  .its('body').should('not.be.undefined')
  // wraps "body" DOM element to allow
  // chaining more Cypress commands, like ".find(...)"
  .then(cy.wrap)
}

it('gets the post', () => {
  cy.visit('index.html')
  getIframeBody().find('#run-button').should('have.text', 'Try it').click()
  getIframeBody().find('#result').should('include.text', '"delectus aut autem"')
})