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

Cypress移除target属性后Google Play按钮仍新开窗口问题求助

解决Cypress中Google Play按钮移除target后仍新开窗口的问题

问题描述

使用Cypress测试App Store和Google Play下载按钮时,两者HTML结构一致,均带有target="_blank"属性。通过.invoke('removeAttr', 'target').click()可让App Store按钮在当前窗口打开,但Google Play按钮执行相同操作后仍会新开窗口,尝试设置target='_self'和自定义函数规避默认行为均无效。

相关HTML结构:

<ul class="AppDownloadLinks_List__tY_ff" xpath="1">
  <li class="AppDownloadLinks_ListItem__UuCiZ">
    <a href="https://apps.apple.com/us/app" target="_blank" aria-label="App Store Link (Opens in a new tab)" rel="noreferrer">
      <span class="is-vishidden">App Store Link</span>
      <img class="AppDownloadLinks_Image__AVsMa" alt="App Store" src="/images/app-store.svg">
    </a>
  </li>
  
  <li class="AppDownloadLinks_ListItem__UuCiZ">
    <a href="https://play.google.com/store/apps/" target="_blank" aria-label="Google Play Store Link (Opens in a new tab)" rel="noreferrer">
    <span class="is-vishidden">Google Play Store Link</span>
    <img class="AppDownloadLinks_Image__AVsMa" alt="Google Play Store" src="/images/google-play.png">
    </a>
  </li>
</ul>

核心原因

Google Play按钮的<a>标签大概率绑定了自定义click事件监听,即使移除target属性,前端代码仍会强制触发新窗口打开逻辑,覆盖了Cypress的操作。

解决方案

方案1:直接获取href并访问(最可靠)

跳过模拟点击,直接提取链接地址用cy.visit()访问,绕开前端事件干扰:

clickGooglePlayBtn(): void {
  this.clickMenuButton();
  cy.get(downloadLinks).should('be.visible');

  cy.get(googlePlayButton)
    .should('be.visible')
    .invoke('attr', 'href')
    .then((href) => {
      cy.visit(href);
    });
  
  cy.url().should('include', 'https://play.google.com/store/apps');
  cy.go('back');
}

方案2:阻止默认点击行为后手动跳转

通过on('click')拦截默认跳转行为,再手动访问目标链接:

clickGooglePlayBtn(): void {
  this.clickMenuButton();
  cy.get(downloadLinks).should('be.visible');

  cy.get(googlePlayButton)
    .should('be.visible')
    .on('click', (e) => {
      e.preventDefault(); // 阻止默认跳转
      const href = e.currentTarget.href;
      cy.visit(href);
    })
    .click(); // 触发点击,但默认行为已被拦截
  
  cy.url().should('include', 'https://play.google.com/store/apps');
  cy.go('back');
}

方案3:移除自定义事件监听(针对性场景)

如果确认是自定义事件导致的问题,可尝试移除元素的click事件监听(需匹配前端事件绑定方式):

clickGooglePlayBtn(): void {
  this.clickMenuButton();
  cy.get(downloadLinks).should('be.visible');

  cy.get(googlePlayButton)
    .should('be.visible')
    .invoke('removeAttr', 'target')
    .invoke('off', 'click') // 移除jQuery绑定的click事件
    .click();
  
  cy.url().should('include', 'https://play.google.com/store/apps');
  cy.go('back');
}

注意:方案3依赖前端事件的绑定方式,若为原生JS绑定的事件,需明确事件处理函数引用才能移除,实用性较低,优先推荐方案1或2。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 08:27:03