Skip to content

Cypress - 子窗口

Cypress - 处理新浏览器标签页(子窗口)

Section titled “Cypress - 处理新浏览器标签页(子窗口)”

Cypress 设计上是在单个浏览器标签页的上下文中运行。当应用程序试图在新的标签页中打开链接(通常使用 target="_blank" HTML 属性)时,Cypress 无法直接控制这个新的标签页。但是,有一些有效的策略来处理这些场景。

对于链接到同源 URL 并在新标签页打开的情况,一个常见的解决方法是通过程序移除链接的 target 属性。这会使得链接在当前标签页中打开,从而允许 Cypress 继续与内容进行交互。Cypress 使用 jQuery 的 removeAttr() 方法,通过 cy.invoke() 命令来达到此目的。

移除 target="_blank" 后,点击链接会将新页面内容加载到同一标签页中。执行必要操作后,可以使用 cy.go('back') 命令返回到上一页。

对于涉及在新标签页中打开跨域 URL 且需要交互的场景,Cypress 提供了 cy.origin() 命令。该命令允许你切换上下文,并在具有不同源的页面上执行命令。但是,本教程将重点介绍用于同源链接的 removeAttr 技术,如下所示范例。

考虑以下打开新窗口的 HTML 代码片段:

<!-- HTML Example -->
<a href="/windows/new" target="_blank">Click Here</a>

以下是如何处理打开同源 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');
});
});

当你运行此测试时:

  • Cypress 导航到初始页面。
  • 它找到链接并使用 .invoke('removeAttr', 'target') 移除会使其在新标签页中打开的属性。
  • .click() 随后在当前标签页中打开链接的 href。
  • 断言会验证新加载页面的 URL 和内容。
  • cy.go('back') 成功导航回上一页,因为历史记录保存在单个标签页内。

这种方法对于测试工作流中在新标签页打开与待测应用程序在同一域下的页面非常有效。