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

TestCafe中使用Ctrl+鼠标点击无法在新标签页打开链接

解决TestCafe中Ctrl+点击无法在新标签页打开链接的问题

问题分析

你的测试代码逻辑无语法错误,但链接仍在当前标签页打开,大概率是页面自定义JavaScript事件阻止了浏览器默认的新标签页打开行为,或是modifiers参数的模拟方式未被页面事件正确识别。

可行解决方案

方案1:手动控制修饰键的按下与释放

替换原click方法的参数式调用,改为先按住Ctrl键再点击,完成操作后释放按键:

import { fixture, Selector } from 'testcafe';
 
fixture`Fixture import`.only
    .page('https://testcafe.io/documentation/402634/guides');
 
test('Click a button', async t => {
    await t.maximizeWindow();
    const ab = Selector('a[href="/documentation/402837/guides/basic-guides/assertions"]');
    
    // 手动按住Ctrl键,点击后释放
    await t.pressKey('ctrl');
    await t.click(ab);
    await t.releaseKey('ctrl');
    
    await t.wait(5000);
});

方案2:用ClientFunction模拟原生鼠标事件

如果页面JS拦截了默认点击行为,可通过触发原生鼠标事件绕开页面自定义处理:

import { fixture, Selector, ClientFunction } from 'testcafe';
 
// 定义客户端函数,模拟带Ctrl键的原生点击
const openLinkInNewTab = ClientFunction((selector) => {
    const linkElement = selector();
    const clickEvent = new MouseEvent('click', {
        bubbles: true,
        cancelable: true,
        ctrlKey: true
    });
    linkElement.dispatchEvent(clickEvent);
});
 
fixture`Fixture import`.only
    .page('https://testcafe.io/documentation/402634/guides');
 
test('Click a button', async t => {
    await t.maximizeWindow();
    const ab = Selector('a[href="/documentation/402837/guides/basic-guides/assertions"]');
    
    await openLinkInNewTab(ab);
    
    await t.wait(5000);
});

方案3:临时修改链接的target属性

若上述方法均无效,可先给目标链接添加target="_blank"属性,再执行点击操作:

import { fixture, Selector, ClientFunction } from 'testcafe';
 
// 修改链接的target属性为_blank
const setLinkTargetBlank = ClientFunction((selector) => {
    const linkElement = selector();
    linkElement.setAttribute('target', '_blank');
});
 
fixture`Fixture import`.only
    .page('https://testcafe.io/documentation/402634/guides');
 
test('Click a button', async t => {
    await t.maximizeWindow();
    const ab = Selector('a[href="/documentation/402837/guides/basic-guides/assertions"]');
    
    await setLinkTargetBlank(ab);
    await t.click(ab);
    
    await t.wait(5000);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 23:45:29