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.

Handle Multiple tabs in Cypress

Handle Multiple tabs in Cypress

While writing E-2-E automation scripts of any web application it’s mandatory to handle multiple window tabs. In this tutorial, We have covered this topic, “How to handle multiple tabs in the Cypress? “.

cy.get('a[href^="http"]').then(($links) => {
    // Save the number of links
    const numLinks = $links.length;
  
    // Iterate through the links
    for (let i = 0; i < numLinks; i++) {
        // Open the link in a new tab
        cy.wrap($links[i]).invoke('attr', 'target', '_blank').click();
  
        // Switch to the new tab
        cy.get('body').then(($body) => {
            const tabIds = Object.keys($body[0].ownerDocument.defaultView.cy_win);
            cy.wrap(tabIds[tabIds.length - 1]).as('newTabId');
        });
  
        // Perform actions on the new tab
        cy.get('@newTabId').then((tabId) => {
            cy.tab({tabId}).get('h1').should('contain', 'Welcome');
        });
  
        // Close the new tab
        cy.get('@newTabId').then((tabId) => {
            cy.tab({tabId}).close();
        });
  
        // Switch back to the original tab
        cy.get('body').then(($body) => {
            const tabIds = Object.keys($body[0].ownerDocument.defaultView.cy_win);
            cy.wrap(tabIds[0]).as('originalTabId');
        });
        cy.tab({tabId: '@originalTabId'});
    }
});

This code uses Cypress’ .get() method to select all links on the page that begin with “http” and opens each link in a new tab. The code then switches to each new tab, performs some actions on the new tab, closes the tab, and then switches back to the original tab.

Note that,   Cypress.tab command is not a built-in command. But it can be added by installing cypress-tab-commands package, it allows to switch between tabs and window using Cypress commands.

 

 

 

For more interesting blogs . Click here

Special thanks to: 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.