DEV Community

Gurpinder Singh
Gurpinder Singh

Posted on

Handle iframe with Cypress

When you are handle iframe using cypress, sometimes you get
error:Timed out retying after 4000ms: cy.find() failed because athe page updated as a result on this
command, but uou tried to continue the command chain. The subject is no longer attached to the dom, and cypress cannot
requery the page after commands such as cy.find().

Solution:

The issue you're facing with entering text in the textbox inside the iframe using Cypress seems to be due to synchronization problems or timing issues. Cypress commands are chained together and executed asynchronously, which can sometimes lead to race conditions when interacting with iframes.

Here are a few suggestions to handle iframes in Cypress and resolve the issue:

1. Use cy.iframe() and .then() to ensure synchronization:

import "cypress-iframe";

describe("Handling iframes", () => {
  it("Approach", () => {
    cy.visit("https://rahulshettyacademy.com/AutomationPractice/");

    cy.frameLoaded("#courses-iframe");

    cy.iframe()
      .find("a[href*='consulting']")
      .eq(0)
      .click()
      .then(($iframe) => {
        $iframe.find("#username").type("shishir");
      });
  });
});

Enter fullscreen mode Exit fullscreen mode

2. Retry the operation using Cypress' retry() method:

import "cypress-iframe";

describe("Handling iframes", () => {
  it("Approach", () => {
    cy.visit("https://rahulshettyacademy.com/AutomationPractice/");

    cy.frameLoaded("#courses-iframe");

    cy.iframe()
      .find("a[href*='consulting']")
      .eq(0)
      .click();

    cy.iframe()
      .find("#username")
      .should("be.visible")
      .retry(3) // Retry the operation if the element is not immediately found
      .type("shishir");
  });
});

Enter fullscreen mode Exit fullscreen mode

3. Use a combination of cy.wrap() and .then() to interact with the iframe content:

import "cypress-iframe";

describe("Handling iframes", () => {
  it("Approach", () => {
    cy.visit("https://rahulshettyacademy.com/AutomationPractice/");

    cy.frameLoaded("#courses-iframe");

    cy.get("#courses-iframe").then(($iframe) => {
      const iframe = $iframe.contents();
      cy.wrap(iframe.find("a[href*='consulting']").eq(0)).click();
      cy.wrap(iframe.find("#username")).type("shishir");
    });
  });
});

Enter fullscreen mode Exit fullscreen mode

Choose the method that fits best with your workflow and try handling the iframe content accordingly. These approaches aim to mitigate timing issues by synchronizing Cypress commands properly within the iframe context. Adjustments might be necessary based on the specific behavior of the website or iframe content.

Thanks for reading,
Dgi Host.com

Top comments (0)