open a link within an iframe in the same tab

Viewed 569

I am trying to click on a link that is within iframe in Cypress. The link opens in the next tab and the test fails.

cy.get('iframe.body').wait(1000).its('0.contentDocument.body')
  .find('a').contains('Click').click();

To fix the issue used something like this to make the new page open on the same tab. But its not working:

cy.get('iframe.body').wait(1000).its('0.contentDocument.body')
  .find('a').contains('Click')
  .invoke('removeAttr', 'target').click();

Element looks something like this:

<iframe class="body" data-flexie-id="3" data-flexie-parent="true" src="messages/1.html" style="">
</iframe>
<p>
  <a href="https://Thisisalink/91cf-a6c3792a5cc5" target="_blank">Click</a>
</p>
3 Answers

target="_parent" opens the link in the same page as the parent. Edit: I suppose you don't want the <a> to be in the <iframe>, right?

<iframe class="body" data-flexie-id="3" data-flexie-parent="true" src="messages/1.html" style=""></iframe>
<p><a href="https://Thisisalink/91cf-a6c3792a5cc5" target="_blank">Click</a></p>

I had found 2 solutions:

  1. Copy the link and visit it:

Cypress.Commands.add("ui_clickTagButton", (buttonSelector) => {
    cy.log('ui_clickTagButton - start')

    cy.wrap(buttonSelector)
        .should('have.prop', 'href')
        .then(href => cy.visit(href))

    cy.log('ui_clickTagButton - End')
})
  1. Remove the target attribute using the Jquery - incorporated in cypress, then click:
Cypress.Commands.add("ui_removeATagTargetAttributeAndCick", (aTagSelector) => {
    cy.log('ui_clickAnchorTagButton')
    cy.get(aTagSelector)
        .then((aTagElement) => {
            Cypress.$(aTagElement).removeAttr("target");
            cy.get(aTagElement)
                .click({force: true})
                .should('not.exist')
        })
})

So for your case I would Use the second one:

cy.get('iframe.body').wait(1000).its('0.contentDocument.body').find('a')
   .then(button => {
       cy.ui_removeATagTargetAttributeAndCick(button)
   })

Your HTML indicates the link is outside the iframe, if so you don't need to select it.

Using .find('a') is similar to .within(() => ...), but since <a> is not within the iframe, your strategy to remove the target will work if you target the <a> directly

cy.contains('a', 'Click')  
  .invoke('removeAttr', 'target')
  .click();
Related