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

点击按钮后如何从注入脚本中提取动态URL用于Cypress测试?

问题描述

我有如下DOM按钮元素:

<a id="ctl00_MainContent_UndoButton" class="a-button a-button--cancel dd-data-link" href="javascript:__doPostBack('ctl00$MainContent$UndoButton','')"> Undo </a>

点击该按钮后会弹出新的动态URL窗口,同时页面会注入如下脚本:

//<![CDATA[
ToggleTempChanged();TogglePermaChanged()
;window.open('**/products/Car/EndTempAdjustment.aspxenc
=Y/qlHvbv+Gt2rmvC4GL1GzEO87O1bd8H91aPhk96iKLRMC+yw
MY3gWzR7jpKnJVPaIz+srgg 
NtdnpsEudpo4lEa7ccLMPe2PXXQlxREtp8nsWkPq
7qKCBnVCt7n0m7f953bwfRYXrngveDlNLAqC 
wjpPP6eIp6Sz+oEtMBkjUEHJd4jztk2IEJcsHskdXH6H**');

var Page_ValidationActive = false;
if (typeof(ValidatorOnLoad) == "function") {
    ValidatorOnLoad();
}

function ValidatorOnSubmit() {
    if (Page_ValidationActive) {
        return ValidatorCommonOnSubmit();
    }
    else {
        return true;
    }
}
    
document.getElementById('ctl00_RequiredFieldValidator1').dispose = 
function() {
    Array.remove(Page_Validators, 
document.getElementById('ctl00_RequiredFieldValidator1'));
}

document.getElementById('ctl00_RegularExpressionValidator1').dispose = 
function() {
    Array.remove(Page_Validators, 
document.getElementById('ctl00_RegularExpressionValidator1'));
}
//]]>

我尝试过stub(存根)、移除属性等方法对新窗口进行测试但未成功,也查阅过动态URL打开新窗口的相关方案。请问如何从上述注入脚本中提取动态URL?我计划提取后用cy.visit访问该URL开展测试。

解决方案

方法1:拦截window.open捕获URL

在Cypress中提前存根window.open,直接获取它的调用参数(即目标动态URL),步骤如下:

let newWindowUrl;

// 存根window.open并记录URL
cy.window().then(win => {
  cy.stub(win, 'open').callsFake((url) => {
    newWindowUrl = url;
    return { close: () => {} }; // 返回模拟窗口对象避免报错
  });
});

// 点击目标按钮触发脚本注入
cy.get('#ctl00_MainContent_UndoButton').click();

// 验证并访问URL
cy.wrap(newWindowUrl).should('include', '/products/Car/EndTempAdjustment.aspx');
cy.visit(newWindowUrl);

方法2:从注入的脚本内容中提取URL

如果拦截window.open不生效,可直接从页面脚本中匹配提取:

cy.get('script').then(scripts => {
  // 筛选包含目标URL特征的脚本
  const targetScript = [...scripts].find(script => 
    script.textContent.includes('/products/Car/EndTempAdjustment.aspx')
  );

  if (targetScript) {
    // 用正则匹配window.open中的URL内容
    const urlMatch = targetScript.textContent.match(/window\.open\('([^']+)'\)/);
    if (urlMatch && urlMatch[1]) {
      // 去除URL中的换行和空白字符
      const dynamicUrl = urlMatch[1].replace(/\s+/g, '');
      cy.visit(dynamicUrl);
    }
  }
});

方法3:直接触发__doPostBack后提取URL

按钮点击本质是调用__doPostBack函数,可直接触发后再提取URL:

cy.window().then(win => {
  // 触发回发逻辑
  win.__doPostBack('ctl00$MainContent$UndoButton', '');
  cy.wait(500); // 可替换为更可靠的断言(如等待脚本加载)代替固定等待

  // 复用方法2的提取逻辑
  cy.get('script').then(scripts => {
    const targetScript = [...scripts].find(script => 
      script.textContent.includes('/products/Car/EndTempAdjustment.aspx')
    );
    if (targetScript) {
      const urlMatch = targetScript.textContent.match(/window\.open\('([^']+)'\)/);
      if (urlMatch && urlMatch[1]) {
        const dynamicUrl = urlMatch[1].replace(/\s+/g, '');
        cy.visit(dynamicUrl);
      }
    }
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 21:17:19