How to Handle New Tab in Cypress: Simple Fix and Best Practices
Cypress does not support multiple browser tabs, so to handle a new tab, use
cy.stub or cy.invoke('removeAttr', 'target') to prevent opening a new tab and force the link to open in the same tab. Then continue testing in the current tab.Why This Happens
Cypress runs tests inside a single browser tab and does not support switching between multiple tabs or windows. When a link has target="_blank", it tries to open a new tab, but Cypress cannot control or access that new tab. This causes tests to fail or commands to hang.
javascript
cy.get('a#new-tab-link').click();
Output
Error: Cypress detected a new tab or window was opened, which is not supported.
The Fix
To fix this, remove the target attribute from the link before clicking it. This forces the link to open in the same tab, allowing Cypress to continue testing normally.
javascript
cy.get('a#new-tab-link').invoke('removeAttr', 'target').click();
Output
Test continues successfully in the same tab without errors.
Prevention
Always avoid opening new tabs in Cypress tests by removing target="_blank" attributes or stubbing window.open calls. This keeps tests stable and easier to maintain.
- Use
invoke('removeAttr', 'target')on links before clicking. - Stub
window.opento prevent new tabs. - Design your app or test environment to open links in the same tab when testing.
Related Errors
Other common errors include:
- Cannot switch to new window: Cypress does not support
cy.switchToWindow()like Selenium. - Commands hanging after click: Happens when a new tab opens and Cypress loses control.
Quick fix: prevent new tabs by removing target or stubbing window.open.
Key Takeaways
Cypress cannot control multiple tabs; always test in a single tab.
Remove the 'target' attribute from links to prevent new tabs.
Stub 'window.open' to block new tab openings during tests.
Design tests and apps to avoid new tabs for stable automation.
Use 'invoke("removeAttr", "target")' before clicking links that open new tabs.