mcpField
C
contentsquare-react-native-sdk

contentsquare-react-native-sdk

github.com/contentsquare开发242 次安装1 周前更新
代码仓库

关于 contentsquare-react-native-sdk

帮助 AI Agent 在客户端应用中集成或升级 Contentsquare React Native SDK。流程要求先检查项目状态,并涵盖安装、追踪、身份、隐私和会话回放。

主要功能

  1. 01执行 Contentsquare 项目健康检查
  2. 02指导 SDK 安装与配置
  3. 03涵盖屏幕、事件和交易追踪
  4. 04说明身份与隐私 API
  5. 05介绍会话回放控制

适用场景

  1. 01在 React Native 应用中添加 Contentsquare
  2. 02升级现有 SDK 集成
  3. 03排查项目配置问题
  4. 04实现屏幕追踪和会话回放

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/contentsquare/agents --skill contentsquare-react-native-sdk

安装后在 Claude Code 中输入/contentsquare-react-native-sdk确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

references/
api-reference.md
common-patterns.md
compatibility.md
debugging-and-tooling.md
in-app-features.md
migration.md
screen-tracking.md
session-replay.md
webview-tracking.md

详细介绍

Contentsquare React Native SDK 集成

此技能可帮助 AI Agent 在客户端应用中集成或升级 Contentsquare React Native SDK。

必须先执行——Contentsquare 项目健康检查

在对话中进行任何 Contentsquare 相关工作之前——包括集成、调试、配置问题和代码更改——都要执行此健康检查,每次对话仅执行一次。不得跳过,也不得拖到任务后续阶段再执行。

  1. 先告知用户。 告诉用户你接下来要做什么,例如:

    “开始之前,我会快速检查你的 Contentsquare 项目:请提供数据源 ID(如果没有,我会读取应用的 bundle ID),然后我会调用 Contentsquare 健康检查端点,并向你展示当前项目配置。之后我们再继续。”

  2. 先询问用户的 Contentsquare 数据源 ID。 例如:“你有 Contentsquare 数据源 ID 吗?可能有一个或多个,例如 Android 和 iOS 各一个。如果有,请告诉我每个 ID 对应的平台。” 仅使用用户提供的 ID,绝不能自行编造。

    • 用户提供了一个或多个数据源 ID → 仅通过数据源 ID 检查(v3)。跳过第 3 步。
    • 用户只有环境 ID → 仅通过 bundle ID 检查(v2):环境 ID 不是数据源 ID,不能用于 v3 路径。
    • 用户没有、不知道或跳过了此问题 → 仅通过 bundle ID 检查(v2)。
  3. 解析 bundle ID(仅在没有数据源 ID 时)——React Native 应用有两个 bundle ID,而且它们通常是不同的字符串。 分别解析每个平台的 ID,绝不能假设它们相同。

    平台读取位置
    Androidandroid/app/build.gradle(.kts) 中的 applicationId(如无,则使用 namespace,或 AndroidManifest.xml 中的 package)
    iOSios/<App>.xcodeproj/project.pbxproj 中的 PRODUCT_BUNDLE_IDENTIFIER(或 Info.plist 中的 CFBundleIdentifier),并解析任何 $(...) 变量
  4. 调用端点——只能使用一个版本,绝不能同时使用两个版本。 平台部分必须是字面值 ios 或 android。React Native 不是有效的平台值,绝不能发送。

    使用数据源 ID(v3)时,每个 ID 调用一次:

    curl -s "https://mobile-production.content-square.net/healthcheck/android/config/v3/<dataSourceId>.json"
    curl -s "https://mobile-production.content-square.net/healthcheck/ios/config/v3/<dataSourceId>.json"
    

    根据用户提供的平台查询每个 ID。如果平台未知,则在项目中存在的每个平台上查询:某个平台返回非 200,只表示该数据源尚未为该平台设置。

    如果某个 ID 在所有查询的平台上都未返回 200,请告知用户——它可能是环境 ID,也可能是拼写错误——并询问是否可以在代码中查找数据源 ID:该 ID 是传递给 StartConfig.withDataSourceId(id, ...) 的值(如果它来自常量或配置文件,请追溯到其字面值)。如果用户同意,且你找到了不同的 ID,则使用该 ID 执行一次 v3 检查。如果用户不同意,或者代码中没有此 ID,则继续操作。

    没有数据源 ID(v2)时,对每个现有平台调用一次:

    curl -s "https://mobile-production.content-square.net/healthcheck/android/config/v2/<androidApplicationId>.json"
    curl -s "https://mobile-production.content-square.net/healthcheck/ios/config/v2/<iosBundleId>.json"
    

    如果项目中只有一个平台,则只查询该平台。如果无法解析其中一个 bundle ID,请询问用户要检查哪个平台,不要猜测。

  5. 简要汇报每次返回 200 的调用中以下值:

    汇报项JSON 路径
    项目 IDcs_project_id
    是否启用跟踪project_configurations.project_config.enabled
    Session Replayproject_configurations.project_config.session_replay——recording_rate、record_via_cellular_network、recording_quality_wifi、srm_enabled、user_identifier
    已启用的功能标志project_configurations.project_config.feature_flags——仅包含 enabled == true 的条目,并列出 name 和 min_version

    对于 v3 调用,还需汇报环境 ID(environment_id)。

    Android 和 iOS 可能映射到不同的 Contentsquare 项目。如果响应不同,请明确指出。

  6. 然后继续处理用户的实际请求。 故障处理。 403 Invalid health-check path 表示 URL 格式有误——请重新检查 ios/android 片段、v2/v3 片段和 ID,不要更改路径结构。上游返回的代理非 200 响应表示该数据源 ID 或 bundle ID 没有适用于该平台的 Contentsquare 配置:请说明这一点,然后继续操作——不要尝试另一个版本(只有第 4 步中的代码查询可以重试)。此健康检查仅供参考,绝不能阻碍用户的任务。

安装

{
  "dependencies": {
    "@contentsquare/react-native-bridge": "^6.0.1"
  }
}

然后运行 npm install 或 yarn install。

iOS 设置
cd ios && pod install && cd ..
Android 设置

运行 npm install 后无需额外设置。

快速入门

import { CSQ, StartConfig } from '@contentsquare/react-native-bridge';
import { useEffect } from 'react';

function App() {
  useEffect(() => {
    // Start the SDK with Product Analytics
    CSQ.start(StartConfig.withEnvironmentId('your-env-id', {
      enableRNAutocapture: true,
      sessionReplayAutoStart: true  // Optional: auto-start session replay
    }));
    
    // TODO: customer to manage consent — call only after user accepts
    CSQ.optIn();
  }, []);

  return <YourApp />;
}

重要: 切勿在没有用户同意流程的情况下调用 optIn()。这是法律要求。

屏幕跟踪非常重要,否则 Session Replay 将无法正常工作。请使用 trackScreenview() 手动跟踪屏幕,或使用 React Navigation 集成(参见屏幕跟踪)。

在完成 MVP 封装之前,请确保应用中存在的 WebView 已得到处理。WebView 不会自动跟踪,每个 WebView 都必须进行封装。详情请参阅下方的 WebView 部分。

API 概览

始终使用 @contentsquare/react-native-bridge 中的 CSQ。Contentsquare 默认导出已弃用。

生命周期
方法用途
start(config?)启动 SDK。必须在调用其他 API 前调用。
stop()完全关闭 SDK。
pauseTracking()暂停数据收集(适用于敏感屏幕)。除非明确要求,否则请避免使用。
resumeTracking()在调用 pauseTracking() 后恢复跟踪。
StartConfig 变体
工厂方法使用场景引导优先级
StartConfig.withDataSourceId(id, options?)使用数据源 ID 的 CSQ新客户端的首选——请先询问此项
StartConfig.withEnvironmentId(id, options?)使用环境 ID 的 Product Analytics如果没有数据源 ID,则作为第二选择
StartConfig.dxa()仅 Digital Experience Analytics(默认)仅作为后备方案——没有任何 ID 可用,或明确要求仅使用 DXA 时

withDataSourceId 和 withEnvironmentId 接受相同的 AnalyticsOptions 对象(参见下方的 AnalyticsOptions 部分)。StartConfig.dxa() 不接受参数——它没有 AnalyticsOptions 参数。

推荐的引导流程:

  1. 询问用户:“您有 Contentsquare 数据源 ID 吗?”(如果用户已在健康检查期间回答,则跳过此问题)。如果有,则使用 StartConfig.withDataSourceId(id, ...)。
  2. 如果没有,询问:“您有环境 ID 吗?” 如果有,则使用 StartConfig.withEnvironmentId(id, ...)。
  3. 只有在两种 ID 都不可用(或用户明确要求仅使用 DXA)时,才回退到 StartConfig.dxa()。

不要编造 ID。不要在未询问的情况下默认使用 DXA。

隐私
方法用途
optIn()允许设备参与跟踪。立即开始跟踪。
optOut()永久退出跟踪。直到调用 optIn() 或重新安装应用前,跟踪都会停止。
身份
方法上下文用途
identify(userIdentifier)Product Analytics设置用户身份。不同的 ID 会触发新会话。
resetIdentity()Product Analytics清除身份。会触发新会话。
sendUserIdentifier(userIdentifier)DXA发送经过哈希处理的用户 ID。最多 100 个字符。
屏幕跟踪
方法用途
trackScreenview(screenName, customVars?)跟踪屏幕浏览,可选附带自定义变量。

CustomVar 结构:{ index: number, key: string, value: string }——index(1-20)、key(最多 50 个字符)、value(最多 255 个字符)。

React Navigation 示例请参见屏幕跟踪集成。

交易
import { CSQ, Currency } from '@contentsquare/react-native-bridge';

CSQ.trackTransaction({
  price: 29.99,
  currency: Currency.USD,
  id: 'order_123'
});

Currency 是一个 ISO 4217 枚举(例如,Currency.USD、Currency.EUR)。

自定义事件和属性
方法用途
trackEvent(eventName, properties?)跟踪命名事件,可选携带属性。
addDynamicVar(key, value, onError?)添加会话级动态变量(仅限 DXA)。
addUserProperties(properties)设置用户级属性(仅限 PA)。
addEventProperties(properties)为所有后续事件设置属性(仅限 PA)。
removeEventProperty(name)移除一个事件属性。
clearEventProperties()移除所有事件属性。

属性值必须是 string、number、boolean 或 bigint。其他类型将被静默忽略。

动态变量(仅限 DXA):

  • key:字符串(最多 50 个字符)
  • value:字符串(最多 255 个字符)或无符号整数(0 至 2^32-1)
  • onError:可选的验证错误回调
会话回放
方法用途
startSessionReplay()按需启动会话回放。若在调用 start() 时传入了 sessionReplayAutoStart: false,请使用此方法。仅限一次——这不是重启 API。
stopSessionReplay()按需停止会话回放,但不停止 SDK。不可逆——在同一 SDK 生命周期内,之后无法重新启动 SR。

按需会话回放——在 SDK 启动时禁用自动启动,并手动控制:

CSQ.start(StartConfig.dxa());
// Note: sessionReplayAutoStart defaults to false, no need to pass options

// later, when you want SR to start (e.g., entering a checkout flow):
CSQ.startSessionReplay();

// and to stop it (final -- no restart afterwards):
CSQ.stopSessionReplay();

startSessionReplay / stopSessionReplay 仅用于启动和停止,不用于暂停和恢复。调用 stopSessionReplay() 后,SR 将保持关闭,直到下一个 SDK 生命周期。

会话元数据(获取回放链接)

访问会话信息,包括回放 URL。onMetadataChange 返回一个取消订阅函数——调用它可移除监听器(例如,在组件卸载时):

import { useEffect } from 'react';

useEffect(() => {
  const unsubscribe = CSQ.onMetadataChange((metadata) => {
    console.log('Session Replay URL:', metadata.sessionReplayUrl);
    console.log('Session ID:', metadata.sessionID);
    console.log('User ID:', metadata.userID);
  });

  return unsubscribe; // Cleanup on unmount
}, []);

Metadata 字段:projectID、environmentID、userID、identity、sessionID、sessionReplayUrl(字符串或 null)。

调试
API用途
setLogLevel(LogLevel)设置日志级别(info、verbose 等)
setLogChannel(LogChannel)设置日志输出渠道
logToConsole()启用控制台日志记录
AnalyticsOptions(由 withDataSourceId 和 withEnvironmentId 共用)

StartConfig.dxa() 不接受 AnalyticsOptions。以下选项仅适用于 withDataSourceId 和 withEnvironmentId。

所有字段均可为空(undefined = 原生默认行为)。

字段类型用途
enableRNAutocaptureboolean?启用 React Native 交互自动捕获(PA)
sessionReplayAutoStartboolean?若为 true,则在 SDK 启动时开始 SR。默认值:false
uploadIntervalnumber?上传间隔(毫秒;默认值:15000)
baseUrlstring?自定义 API 端点(例如,用于欧盟数据驻留)
disablePageviewAutocaptureboolean?禁用自动屏幕跟踪
disableInteractionAutocaptureboolean?禁用自动触摸跟踪(仅限 iOS)
disableInteractionTextCaptureboolean?禁用交互中的文本捕获(仅限 iOS)
disableInteractionAccessibilityLabelCaptureboolean?禁用无障碍标签捕获(仅限 iOS)
disablePageviewTitleAutocaptureboolean?禁用页面标题捕获(仅限 iOS)
enablePushNotificationAutocaptureboolean?捕获推送通知事件
enablePushNotificationTitleAutocaptureboolean?捕获推送通知标题
enablePushNotificationBodyAutocaptureboolean?捕获推送通知正文

会话回放遮罩

全局遮罩(setDefaultMasking)
import { CSQ } from '@contentsquare/react-native-bridge';

// Mask everything by default
CSQ.setDefaultMasking(true);

// Unmask everything (use with caution - privacy risk)
CSQ.setDefaultMasking(false);

重要:

  • setDefaultMasking 接受的是布尔值,而不是配置对象。它会对全局内容进行全有或全无的遮罩。
  • 必须在 CSQ.start(...) 之后调用 setDefaultMasking。在 start() 之前调用无效。
按组件限制遮罩
import { CSQMask } from '@contentsquare/react-native-bridge';

<CSQMask isSessionReplayMasked={true}>
  <Text>Sensitive content</Text>
</CSQMask>

注意:isSessionReplayMasked 控制 Session Replay 的视觉遮罩。使用 allow* 属性还可以控制 Product Analytics 事件数据。

使用 allow* 属性进行精细控制(Product Analytics)
<CSQMask 
  isSessionReplayMasked={true}  // Masks visual content in Session Replay
  allowText={false}             // Prevents text in PA events
  allowInteraction={false}      // Prevents interaction tracking in PA events
>
  <TextInput placeholder="Password" />
</CSQMask>

重要:只有 isSessionReplayMasked 会影响 Session Replay 的视觉遮罩。allow* 属性控制 Product Analytics 事件数据的采集。

CSQMask 属性
属性类型默认值用途功能
isSessionReplayMaskedboolean?true是否遮罩视觉内容Session Replay
ignoreTextOnlyboolean?false仅忽略文本(与 allow* 冲突)Product Analytics
allowInnerHierarchyboolean?false允许在事件中包含内部视图层级Product Analytics
allowPropsboolean?false允许在事件中包含视图属性Product Analytics
allowTextboolean?false允许在事件中包含文本内容Product Analytics
allowInteractionboolean?false允许在事件中跟踪交互Product Analytics
allowAccessibilityLabelboolean?false允许在事件中包含无障碍标签Product Analytics

重要:只有 isSessionReplayMasked 会影响 Session Replay 的视觉遮罩。allow* 属性控制 Product Analytics 事件数据的采集。当 ignoreTextOnly 为 true 时,所有 allow* 属性都会被忽略。

高阶组件遮罩
import { withCSQMask } from '@contentsquare/react-native-bridge';

const MaskedComponent = withCSQMask(SensitiveComponent, {
  isSessionReplayMasked: true,  // SR visual masking
  allowText: false              // Optional: PA event data masking
});

屏幕跟踪集成

手动跟踪
import { CSQ } from '@contentsquare/react-native-bridge';
import { useEffect } from 'react';

function ProductScreen() {
  useEffect(() => {
    CSQ.trackScreenview('ProductDetails', [
      { index: 1, key: 'product_id', value: '12345' }
    ]);
  }, []);

  return <ProductView />;
}
React Navigation 集成

使用 React Navigation 的导航状态监听器自动跟踪屏幕浏览:

import { NavigationContainer } from '@react-navigation/native';
import { CSQ } from '@contentsquare/react-native-bridge';

function App() {
  const navigationRef = useRef();
  const routeNameRef = useRef();

  return (
    <NavigationContainer
      ref={navigationRef}
      onReady={() => {
        routeNameRef.current = navigationRef.current?.getCurrentRoute()?.name;
      }}
      onStateChange={() => {
        const previousRouteName = routeNameRef.current;
        const currentRouteName = navigationRef.current?.getCurrentRoute()?.name;

        if (previousRouteName !== currentRouteName) {
          CSQ.trackScreenview(currentRouteName);
        }

        routeNameRef.current = currentRouteName;
      }}
    >
      <YourNavigator />
    </NavigationContainer>
  );
}

更多示例请参阅 references/screen-tracking.md。

WebView 跟踪

WebView 不会自动跟踪。使用 CSQWebView 包装它们,以启用原生内容与 Web 内容之间的会话串联。网页必须包含 WebView 模式下的 Contentsquare Web Tracking Tag。

import { CSQWebView } from '@contentsquare/react-native-bridge';
import { WebView } from 'react-native-webview';

<CSQWebView>
  <WebView source={{ uri: 'https://example.com' }} />
</CSQWebView>

旧版包装器(已弃用,请使用 CSQWebView):

import { CSWebView } from '@contentsquare/react-native-bridge';

<CSWebView>
  <WebView source={{ uri: 'https://example.com' }} />
</CSWebView>

重要规则

  • 首先询问环境 ID:集成前,向用户询问其 Contentsquare 环境 ID(或数据源 ID——复用健康检查中的答案)。不要假定仅使用 DXA 模式,不要编造 ID,也不要跳过此步骤。
  • 检查 WebView:集成时,在代码库中搜索是否使用了现有 WebView(react-native-webview、WebView 组件)。WebView 不会自动跟踪——每个 WebView 都必须用 CSQWebView 包装。
  • 在调用任何其他 CSQ 方法之前,使用适当的配置调用 start(config)
  • 调用 optIn() 之前务必实现同意流程——切勿自动选择加入
  • optOut() 会一直生效,直到调用 optIn() 或重新安装应用
  • identify() 仅适用于 Product Analytics;sendUserIdentifier() 仅适用于 DXA
  • 属性值必须是 string、number、boolean 或 bigint——其他类型(数组、对象)会被静默忽略或可能导致意外行为
  • CustomVar 限制:键最长 50 个字符;字符串值最长 255 个字符;数字范围为 0 到 2^32-1
  • userIdentifier:最多 100 个字符
  • 需要 React Native >= 0.71.0(bridge v6.2.0+ 支持从 0.71.0 开始的所有版本)
  • 仅支持 Android 和 iOS(不支持 Web、Expo Go 或桌面端)
  • 屏幕名称、事件名称或属性值中切勿暴露 PII(电子邮箱、密码、真实姓名)
  • 切勿硬编码环境 ID——请使用配置或环境变量
  • 有关 Expo、混合应用和已知限制,请查看 兼容性指南

自动采集(Product Analytics)

自动采集无需手动埋点,即可自动跟踪用户交互和屏幕导航。

前提条件

在 babel.config.js 中安装 Babel 插件:

module.exports = {
  presets: ['module:@react-native/babel-preset'],
  plugins: ['@contentsquare/react-native-bridge/babel'],
};

Babel 插件需要 @babel/plugin-transform-react-display-name 才能在事件中包含组件名称。React Native 的默认预设通常已提供此插件。

Monorepo 设置:如果项目使用 monorepo 结构(Yarn Workspaces、pnpm、Lerna、Nx、Turborepo 等),请确保将该插件添加到项目中所有相关的 babel.config.js 文件,包括包含 React Native 代码的任何软件包中的配置文件。

启用自动捕获
import { CSQ, StartConfig } from '@contentsquare/react-native-bridge';

CSQ.start(StartConfig.withEnvironmentId('your-env-id', {
  enableRNAutocapture: true  // Enable autocapture
}));
导航库兼容性

React Native Bridge 的自动捕获功能兼容以下导航库:

  • React Navigation:5.0 及更高版本
  • React Native Navigation:7.0 及更高版本
自动捕获的内容

自动捕获会自动跟踪:

  • 触摸事件(点击、长按、滑动)
  • 更改事件(文本输入、开关、选择器、滑块)
  • 带显示名称的组件交互
  • 屏幕导航(启用时)
与 Experience Analytics 结合使用

同时使用 Experience Analytics 和 Product Analytics 时,请通过 StartConfig.withDataSourceId 传递 PA 选项:

CSQ.start(StartConfig.withDataSourceId('YOUR_DATA_SOURCE_ID', {
  enableRNAutocapture: true,
  disablePageviewAutocapture: true, // Let Experience Analytics handle screens
}));

Source Maps 与崩溃符号化

如需在生产环境中查看易读的 JavaScript 崩溃堆栈跟踪,请配置 source map 上传:

快速设置
  1. 安装 Contentsquare CLI:

    yarn add @contentsquare/react-native-cli --dev
    
  2. 在项目根目录创建 contentsquare-cli.json,其中包含 API 凭据和 source map 路径

  3. 配置构建脚本:

    • Android:将 apply from: "../../node_modules/@contentsquare/react-native-cli/scripts/contentsquare.gradle" 添加到 app/build.gradle
    • iOS:将 Contentsquare CLI 脚本添加到 Xcode 构建阶段
  4. 添加到 .gitignore:

    contentsquare-cli.json
    contentsquare-sourcemap-info.json
    

有关完整的设置说明和故障排除,请参阅调试与工具。

平台支持

  • Android:全面支持
  • iOS:全面支持(请查看 iOS 兼容性要求)
  • React Native:>= 0.71.0(版本 6.2.0 支持从 0.71.0 起的所有当前及未来版本)
  • Expo:需要 EAS(Expo Application Services)——请参阅兼容性指南
  • 不支持:Web、Windows、macOS、Expo Go

重要提示:混合应用(原生应用中的 React Native 组件)不受官方支持。对于混合代码库,原生屏幕请使用原生 SDK,React Native 屏幕请使用 CSQ bridge。

有关详细的版本矩阵、Expo 配置和已知限制,请参阅兼容性指南。

参考文档

评论

支持 Markdown