How to Handle a New Tab/Child Tab in Cypress?


Cypress has no built-in capability to handle the child tab (switching tab). Cypress is designed to work ONLY in the parent/main tab. So how to handle the child tab now?
As we know the beauty of Cypress is that it allows to modify the DOM using JQuery. i.e. Cypress has a method that calls JQuery to modify DOM.
Approach to handle child windows/tabs:
Removing Target Attribute: Whenever we click on a web element and it opens the link in the child tab, it means the target attribute is applied to that web element. So, now, the easiest way is to open the link on the same browser window by deleting the target attribute.
Now we are going to manipulate the DOM and delete the target attribute. We are going to invoke the jQuery function removeAttr().
cy.get('#opentab').invoke('removeAttr','target').click()
So, we get the web element using cy.get(‘id’). Afterward, we invoke the jQuery method and pass the attribute name using invoke(‘removeAttr’,’ target’), and then perform the click operation by calling click().
Here is a script to handle child tabs:
describe("Handle Child Tab Suite", function () {
it("Child Tab handling test case", function () {
//Parent tab
cy.visit("https://phptravels.com")
//Click on the toggler to perform an action on the SignUp button, which has been allocated with a new tab link.
cy.get('.navbar-toggler').click()
//Remove target
cy.contains('Signup').invoke('removeAttr', 'target').click();
//Child tab
cy.origin("https://phptravels.org/register.php", () =>
{
cy.get('#inputFirstName').type("SUraj")
cy.get('#inputLastName').type("Patil")
})
})
Now the child tab will open inside the parent tab, and if you want to perform any actions on the child tab, you can add commands inside the child tab origin block.
If you want to return to the same URL, you can use the following command in the child tab:
cy.go('back');
Note: The same code is used to handle the open link in the new window.
After adding the script Run the command npx cypress open to open cypress. After opening run the above file. Once you run the test file you will see the below Output:
Reference: https://www.alphabold.com/handling-child-windows-tabs-and-iframes-using-cypress/
Subscribe to my newsletter
Read articles from NonStop io Technologies directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

NonStop io Technologies
NonStop io Technologies
Product Development as an Expertise Since 2015 Founded in August 2015, we are a USA-based Bespoke Engineering Studio providing Product Development as an Expertise. With 80+ satisfied clients worldwide, we serve startups and enterprises across San Francisco, Seattle, New York, London, Pune, Bangalore, Tokyo and other prominent technology hubs.