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

能否捕获react-use-intercom库startTour函数发起的Fetch请求?

问题

我在使用react-use-intercom库的startTour(tourId: number) => void函数时遇到了问题:不管传入的tourId是否有效,这个函数都只返回void,没法像普通Fetch请求那样直接检查响应状态码。但我在网络控制台里能看到这个函数会发起带请求体和响应的Fetch请求,想问下有没有办法在代码里捕获这个请求的结果?

我的调用代码如下:

const handleWhatsNewButtonClick = (): void => {
  boot();
  startTour(123456);
};
解决方案

可以通过以下几种方式捕获请求结果或判断tour是否成功启动:

  • 拦截全局Fetch方法
    重写全局fetch函数,识别Intercom的tour请求并捕获响应状态:

    const originalFetch = window.fetch;
    window.fetch = async (...args) => {
      const response = await originalFetch(...args);
      // 根据网络控制台中请求的URL特征判断是否为tour启动请求
      if (typeof args[0] === 'string' && args[0].includes('/tours/start')) {
        const status = response.status;
        const responseData = await response.clone().json();
        if (status !== 200) {
          console.error('Tour启动失败:', responseData);
          // 这里添加自定义错误处理逻辑,比如提示用户
        }
      }
      return response;
    };
    

    注意要在Intercom初始化前注入该拦截逻辑,确保能捕获到目标请求。

  • 监听Intercom原生事件
    Intercom JS SDK提供了tour相关的事件监听,可直接通过这些事件判断状态:

    import { useEffect } from 'react';
    
    // 在组件中注册监听
    useEffect(() => {
      if (window.Intercom) {
        // 监听tour启动成功事件
        window.Intercom('on', 'tour_started', (tourData) => {
          console.log('Tour已成功启动:', tourData);
          // 处理启动成功后的逻辑
        });
        // 监听错误事件,筛选tour相关错误
        window.Intercom('on', 'error', (error) => {
          if (error.message?.includes('tour')) {
            console.error('Tour操作出错:', error);
            // 处理错误逻辑
          }
        });
      }
    
      // 组件卸载时移除监听
      return () => {
        if (window.Intercom) {
          window.Intercom('off', 'tour_started');
          window.Intercom('off', 'error');
        }
      };
    }, []);
    

    这种方式基于Intercom原生能力,比拦截Fetch更稳定可靠。

  • 通过后端校验Tour有效性
    前端无法直接调用Intercom的管理API,可通过自己的后端代理请求Intercom API,提前校验tourId是否有效:

    const checkTourValidity = async (tourId) => {
      // 调用自己的后端接口,由后端请求Intercom API校验tour
      const response = await fetch(`/api/intercom/check-tour/${tourId}`);
      return response.ok;
    };
    
    const handleWhatsNewButtonClick = async (): void => {
      boot();
      const isTourValid = await checkTourValidity(123456);
      if (isTourValid) {
        startTour(123456);
      } else {
        console.error('无效的Tour ID');
        // 提示用户tour不存在的逻辑
      }
    };
    

    这种方式需要后端配合,但能从根源避免无效tourId的调用。


内容的提问来源于Stack Exchange,提问作者Tian Yue Dong

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 06:36:32