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

Cypress中cy.url()与cy.title()返回空字符串的问题求助

解决Cypress跨域导航后cy.url()/cy.title()返回空的问题

你的问题出在跨域页面导航限制和页面加载等待不充分两个点上,以下是具体修复方案:

方案1:使用Cypress官方推荐的cy.origin()处理跨域(无需关闭安全配置)

Cypress 10+提供cy.origin()命令专门处理跨域场景,比关闭安全配置更安全,代码修改如下:

it.only("Testing new tab opening", ()=>{
  cy.visit("https://rahulshettyacademy.com/AutomationPractice/");
  // 获取目标链接的地址
  cy.xpath("//a[@id='opentab']").invoke('attr', 'href').then((targetUrl) => {
    // 点击打开新页面(无需移除target属性)
    cy.xpath("//a[@id='opentab']").click();
    // 切换到目标域名的上下文
    cy.origin(targetUrl, () => {
      // 在目标域名环境下验证标题和URL
      cy.title().should("eq", "QAClick Academy - A Testing Academy to Learn, Earn and Shine");
      cy.url().should("include", "qaclickacademy");
    });
  });
});

方案2:关闭Chrome跨域安全配置(简单但不推荐生产环境使用)

如果暂时不想用cy.origin(),可以修改Cypress配置文件,关闭Chrome的跨域安全限制:

修改cypress.config.js:

const { defineConfig } = require("cypress");

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      // 保留原有配置
    },
    chromeWebSecurity: false, // 添加这一行关闭跨域安全限制
  },
});

同步更新测试代码,增加页面加载等待:

it.only("Testing new tab opening", ()=>{
  cy.visit("https://rahulshettyacademy.com/AutomationPractice/");
  cy.xpath("//a[@id='opentab']").invoke("removeAttr", "target").click();
  // 先等待URL跳转完成,确认页面加载状态
  cy.url().should("include", "qaclickacademy");
  // 再验证页面标题
  cy.title().should("eq", "QAClick Academy - A Testing Academy to Learn, Earn and Shine");
});

问题根源说明

  1. 原页面域名是rahulshettyacademy.com,点击后跳转的是qaclickacademy.com,属于跨域场景,Cypress默认限制跨域导航,导致无法获取新页面的URL和标题。
  2. 页面跳转是异步操作,直接调用cy.title()时新页面可能还未加载完成,因此返回空字符串。

内容的提问来源于stack exchange,提问作者Shishir Rehan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 04:30:59