Cypress - Child Windows
Cypress - Handling New Browser Tabs (Child Windows)
Section titled “Cypress - Handling New Browser Tabs (Child Windows)”Cypress, by design, operates within a single browser tab context. When an application attempts to open a link in a new tab (often using the target="_blank" HTML attribute), Cypress cannot directly control this new tab. However, there are effective strategies to manage these scenarios.
For links that open new tabs to a same-origin URL, a common workaround is to programmatically remove the target attribute from the link. This causes the link to open in the current tab, allowing Cypress to continue interacting with the content. Cypress uses the jQuery removeAttr() method, invoked via the cy.invoke() command, for this purpose.
After removing target="_blank", clicking the link loads the new page content in the same tab. After performing necessary operations, you can navigate back to the previous page using cy.go('back').
For scenarios involving cross-origin URLs opening in new tabs where interaction is required, Cypress provides cy.origin(). This command allows you to switch context and execute commands on a page with a different origin. However, this tutorial focuses on the removeAttr technique for same-origin links as demonstrated below.
Consider the following HTML snippet where a link opens a new window:
<!-- HTML Example --><a href="/windows/new" target="_blank">Click Here</a>Implementation: Same-Origin New Tab Handling
Section titled “Implementation: Same-Origin New Tab Handling”Here’s an example of how to handle a link that opens a new tab to a same-origin URL:
describe('Tutorialspoint - New Tab Handling', () => { it('Should handle a link that opens in a new tab (same-origin)', () => { cy.visit('https://the-internet.herokuapp.com/windows');
// Find the link, remove the 'target' attribute, and then click it cy.get('.example > a') .invoke('removeAttr', 'target') .click();
// Verify the URL of the new page (now loaded in the same tab) cy.url() .should('include', '/windows/new');
// Perform actions on the new page content if necessary cy.get('h3').should('have.text', 'New Window');
// Navigate back to the parent window's URL cy.go('back');
// Verify we are back on the original page cy.url() .should('include', '/windows'); });});Execution Analysis
Section titled “Execution Analysis”When you run this test:
- Cypress navigates to the initial page.
- It finds the link and uses
.invoke('removeAttr', 'target')to remove the attribute that would cause it to open in a new tab. .click()then opens the link’shrefin the current tab.- Assertions verify the URL and content of the newly loaded page.
cy.go('back')successfully navigates to the previous page because the history is maintained within the single tab.
This approach is effective for testing workflows where new tabs open to pages within the same domain as your application under test.