You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Cypress中获取新窗口实例?现有文档无法完全解决问题

Fixing Cypress New Window Issue When Directly Visiting Target Page

Got it, let's figure out how to fix this tricky Cypress window issue you're facing. I’ve dealt with similar scenarios where apps have strict session or token checks that force a new window even when you try to visit the target page directly. The official docs cover basic window handling, but they don’t account for apps that validate how you arrived at the page. Here are a few actionable solutions:

1. Capture Session Data From the Token Page First

The root issue is likely that the target page (/blabla/page) requires a valid session or token that’s only set when you go through the /blabla/token page. We can capture that session data, then use it to visit the target page without triggering the new window.

it('accesses the target page without a new window', () => {
  // Visit the token page and listen for the new window open event
  cy.visit('http://urlofwebsite:1234/blabla/token')

  cy.window().then((win) => {
    // Stub the window.open method to capture the target URL
    const originalOpen = win.open
    cy.stub(win, 'open').callsFake((url) => {
      cy.wrap(url).as('targetPageUrl')
      // Optional: Call the original open if you want the window to open temporarily
      return originalOpen.call(win, url)
    })
  })

  // Wait for the session to be established, then visit the target page directly
  cy.get('@targetPageUrl').then((targetUrl) => {
    // By this point, the app should have set cookies/tokens from the token page
    cy.visit(targetUrl)
  })

  // Verify the page loads correctly without opening a new window
  cy.url().should('eq', 'http://urlofwebsite:1234/blabla/page')
  // Add a check for a unique element on the target page to confirm it's loaded
  cy.get('[data-testid="target-page-content"]').should('be.visible')
})

2. Extract and Reuse the Authentication Token

If the app uses a token (like a JWT) to validate access, you can intercept the token request from the token page, extract it, and include it when visiting the target page.

it('uses extracted token to bypass new window redirect', () => {
  cy.visit('http://urlofwebsite:1234/blabla/token')

  // Intercept the API call that returns the token (adjust the URL to match your app)
  cy.intercept('GET', '/blabla/api/retrieve-token').as('getToken')
  
  // Wait for the token request to complete
  cy.wait('@getToken').then((interception) => {
    const authToken = interception.response.body.token

    // Visit the target page with the token in headers or as a cookie
    cy.visit('http://urlofwebsite:1234/blabla/page', {
      headers: {
        'Authorization': `Bearer ${authToken}`
      }
    })
  })

  // Confirm the page loads without opening a new window
  cy.url().should('include', '/blabla/page')
})

3. Simulate window.opener to Trick the App

Some apps check if the page was opened via window.opener (i.e., from another window) to allow access. We can mock this property during the initial visit to bypass the check.

it('mocks window.opener to avoid new window', () => {
  cy.visit('http://urlofwebsite:1234/blabla/page', {
    onBeforeLoad(win) {
      // Mock window.opener to make the app think we came from the token page
      win.opener = {
        location: {
          href: 'http://urlofwebsite:1234/blabla/token'
        }
      }
      // Add any other properties your app checks on window.opener if needed
    }
  })

  // Verify the page loads successfully
  cy.get('.target-page-header').should('be.visible')
})

Key Takeaway

All these approaches work by making the app believe you’re accessing the target page through the "legitimate" flow (via the token page). Start with the first method since it mimics the actual user flow most closely, then adjust based on how your app handles session validation.

内容的提问来源于stack exchange,提问作者Yoann Picquenot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:07:37