2

I use Cypress to automate logging in to a web application, protected by an iFrame.

In my Selenium I can use a command to switch to iFrame:

driver.switchTo().frame(driver.findElement(By.xpath(".//*@id='app']/iframe")));

After that I can access iFrame elements as well.

But with Cypress, I don't know the method to switch to frame?

Chillie
  • 1,030
  • 10
  • 28
DuongDD
  • 21
  • 1
  • 2
  • 1
    Possible duplicate: [How do I enter data into a form input in an iframe using cypress?](https://stackoverflow.com/questions/47325258/how-do-i-enter-data-into-a-form-input-in-an-iframe-using-cypress?rq=1) – Joshua Wade Oct 09 '18 at 13:53
  • @JoshuaWade: thank you for your comment, I have found solution to resolve it. cy.get('iframe').then(function ($element) { const $body = $element.contents().find('body') const cyElement = cy.wrap($body) cyElement.find('[class=xxx]').click({force:true}) I hope this can help somebody save your time. – DuongDD Oct 11 '18 at 00:52

3 Answers3

0

In Cypress, you need to install a package called cypress-iframe in order to work on iFrame elements.

Run this command in your terminal to install:

npm install -D cypress-iframe

Import cypress-iframe package to your file:

import 'cypress-iframe';

To load an iFrame, use:

cy.frameLoaded("#id-of-an-iframe");

To find element inside iFrame, start with:

cy.iframe()

Here is the code example on how to use iFrame elements in Cypress:

/// <reference types="Cypress" />
/// <reference types="cypress-iframe" />
import 'cypress-iframe';

describe("Test Suite", () => {
    it("Test Case", () => {

        cy.visit("https://example.com");

        cy.frameLoaded("#iframe-id"); //Load iFrame

        cy.iframe().find("a[href*='services']").eq(0).click();  //click on link inside iFrame
        cy.iframe().find("h1[class*='service-title']").should("have.length", 2);  //assertion

    })
})
Force Bolt
  • 1,117
  • 9
  • 9
0

You can simply do this by writing one method which will go inside the Iframe

getIframeBody(){
        return cy.get('object').its('0.contentDocument').its('body').then(cy.wrap)
    }

Then use this method to procced further like:

this.getIframeBody().xpath("your xpath").click();

If you are writing getIframeBody() method somewhere else then create an object or extends that class and use super keyword to call getIframeBody() method like:

super.getIframeBody().xpath("your xpath").click();
Sudheer Singh
  • 555
  • 5
  • 10
0

It's not really a switch like webdriver io per say, it's more of an access inside the iframe's window content. This link explains it pretty well

starball
  • 20,030
  • 7
  • 43
  • 238
Giggs
  • 851
  • 10
  • 16