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

JS如何检测sendEvent触发的指定序号链接是否存在并捕获跳转状态

问题背景

当前网页的链接跳转通过调用sendEvent('openassignment','mx145', 序号)实现,第三个参数为链接序号,从0开始计数(0对应第一个链接,1对应第二个,以此类推)。需要实现两个核心逻辑:

  • 编程检测指定序号的链接是否存在,例如识别序号为30的链接不存在的场景
  • 跳转结果判断:成功触发跳转时输出everything is ok,链接不存在、未触发跳转时捕获对应异常

现有测试代码如下:

const myTask = () => new Promise(resolve => {
    resolve(sendEvent('openassignment', 'mx145', '0'));
});

async function myt() {
    await myTask().then(() => {
        // 跳转成功需要输出"everything is ok"
        // 链接不存在未跳转时需要捕获该场景
    });
}

myt();
实现方案

现有代码的问题是sendEvent本身不会返回跳转成功/失败的状态,直接resolve Promise无法区分执行结果,需要分两步处理:

1. 提前校验链接存在性

在调用跳转函数前,先统计页面上所有可触发该类跳转的元素总数,和目标序号比对即可判断链接是否存在:

/**
 * 检测指定序号的assignment链接是否存在
 * @param {number} index 链接序号,从0开始
 * @returns {boolean} 存在返回true,不存在返回false
 */
function checkLinkExist(index) {
    // 按实际页面的元素规则选择匹配方式:
    // 方式1:如果跳转元素有统一类名,比如.assignment-link,直接统计数量即可,准确率最高
    // const totalLinks = document.querySelectorAll('.assignment-link').length;
    // 方式2:如果是onclick内联绑定的事件,匹配所有带对应sendEvent调用的元素
    const totalLinks = Array.from(document.querySelectorAll('[onclick]')).filter(el => {
        return el.getAttribute('onclick').includes(`sendEvent('openassignment'`);
    }).length;

    // 序号从0开始,总数大于序号则代表对应索引的元素存在
    return totalLinks > index;
}

2. 监听跳转状态,区分成功/失败

页面触发跳转时会触发pagehide/beforeunload事件,结合短超时逻辑即可判断是否真的完成跳转:

/**
 * 触发指定序号链接跳转,返回Promise区分成功/失败
 * @param {number} linkIndex 目标链接序号
 * @returns {Promise}
 */
const jumpToLink = (linkIndex) => new Promise((resolve, reject) => {
    // 第一步先校验链接是否存在,不存在直接返回失败
    if (!checkLinkExist(linkIndex)) {
        reject(new Error(`序号为${linkIndex}的链接不存在`));
        return;
    }

    let hasJumped = false;
    // 监听页面跳转事件
    const handleJump = () => {
        hasJumped = true;
        resolve();
    };
    window.addEventListener('pagehide', handleJump, { once: true });
    window.addEventListener('beforeunload', handleJump, { once: true });

    // 调用原有跳转函数
    sendEvent('openassignment', 'mx145', String(linkIndex));

    // 超时判断:300ms内没触发跳转事件则判定为跳转失败
    setTimeout(() => {
        window.removeEventListener('pagehide', handleJump);
        window.removeEventListener('beforeunload', handleJump);
        if (!hasJumped) {
            reject(new Error(`序号为${linkIndex}的链接跳转失败`));
        }
    }, 300);
});

async function runTask(targetIndex = 0) {
    try {
        await jumpToLink(targetIndex);
        console.log("everything is ok");
    } catch (err) {
        // 此处捕获链接不存在、跳转未触发的异常
        console.error(err.message);
    }
}

// 调用示例:检测并跳转序号为30的链接
runTask(30);

注意事项

  • 如果页面跳转元素有统一的选择器,优先用统一选择器统计总数,比匹配onclick属性的方式更稳定
  • 300ms的超时阈值可以根据页面实际的JS执行速度调整,只要大于sendEvent内部逻辑的执行耗时即可
  • 事件监听加了once配置,触发一次后会自动移除,不会造成内存泄漏

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.31 22:06:19