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

Chrome扩展获取视频评论数触发页面跳转问题求助

解决Chrome扩展获取视频评论数时页面跳转的问题

问题背景

我正在开发一款Chrome扩展,用于对某网站(TikTok)的搜索结果视频进行排序。搜索关键词后展示的视频列表中不显示评论数,必须打开视频弹窗才能查看。目前已实现评论数获取功能,但现有代码会触发地址栏URL变更并跳离排序页面,需要无需跳转的实现方案。

现有代码的问题分析

当前代码通过模拟鼠标点击视频元素打开弹窗,但点击行为会触发元素的默认导航事件(比如视频容器是<a>标签或绑定了跳转逻辑),导致页面跳转。核心问题是没有阻止点击事件的默认行为,从而引发不必要的页面导航。

解决方案

通过阻止点击事件的默认行为,避免触发页面跳转,同时保留弹窗打开的逻辑。具体从两个层面处理:

  • 在模拟点击时,针对click事件添加preventDefault(),直接阻止默认导航
  • 给视频元素临时添加一次性事件监听器,确保拦截所有可能触发跳转的逻辑

修改后的代码

function waitForElm(selector) {
  return new Promise((resolve) => {
    if (document.querySelector(selector)) {
      return resolve(document.querySelector(selector));
    }

    const observer = new MutationObserver((mutations) => {
      if (document.querySelector(selector)) {
        resolve(document.querySelector(selector));
        observer.disconnect();
      }
    });

    observer.observe(document.body, {
      childList: true,
      subtree: true,
    });
  });
}

function simulateMouseClick(element) {
  const eventNames = [
    'mouseover',
    'mouseenter',
    'mousedown',
    'mouseup',
    'click',
    'mouseout',
  ];
  eventNames.forEach((eventName) => {
    const detail = eventName === 'mouseover' ? 0 : 1;
    const event = new MouseEvent(eventName, {
      detail: detail,
      view: window,
      bubbles: true,
      cancelable: true,
    });
    // 针对click事件阻止默认行为,避免页面跳转
    if (eventName === 'click') {
      event.preventDefault();
    }
    element.dispatchEvent(event);
  });
}

const openAndPrintVideoContent = async (videoTriggerElement) => {
  try {
    // 添加一次性监听器,确保阻止所有可能的默认跳转
    const preventDefaultHandler = (e) => e.preventDefault();
    videoTriggerElement.addEventListener('click', preventDefaultHandler, { once: true });

    simulateMouseClick(videoTriggerElement);

    const commentCountElement = await waitForElm('[data-e2e="browse-comment-count"]');
    console.log("Comment Element Count:" + commentCountElement.textContent);
    const browserCloseElement = await waitForElm('[data-e2e="browse-close"]');

    // 关闭弹窗时也拦截默认行为
    browserCloseElement.addEventListener('click', preventDefaultHandler, { once: true });
    simulateMouseClick(browserCloseElement);

    return commentCountElement.textContent;
  } catch (error) {
    console.log('ERROR: ' + error);
    return 0;
  }
};

const getVideoList = async () => {
  const videos = document.querySelectorAll(".tiktok-18e9va3-DivContainer");
  return videos;
};

const hydrateVideoList = async () => {
  const videos = await getVideoList();
  const resources = [];

  for (const video of videos) {
    const videoInformation = await openAndPrintVideoContent(video);
    resources.push(videoInformation);
  }

  return resources;
};

hydrateVideoList().then((videoComments) => {
  console.log('Video Comments:', videoComments);
});

额外优化建议

如果上述方案仍有跳转问题,可以尝试直接调用网站API获取评论数:

  1. 用浏览器开发者工具的网络面板,找到打开视频时加载评论数的API请求
  2. 复制请求的URL、请求头和参数,用fetch或XMLHttpRequest直接发起请求
  3. 这种方式完全避免DOM操作,效率更高,但需要处理接口的签名、Cookie等验证逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 21:40:14