You need to enable JavaScript to run this app.
导航

API参考

最近更新时间2024.01.16 17:41:55

首次发布时间2022.03.16 11:23:12

本文介绍如何在WebPro中使用SDK调用API。

注意事项

全文的client代表的是SDK实例。如何获取SDK实例,请参见SDK接入

初始化

初始化client实例,初始化配置中可以包含通用事件上下文,通用事件上下文以外的配置只生效一次。
init调用后会开始拉取服务端配置,并拉取异步加载的插件。
client('init', c: InitConfig) => void

interface InitConfig  {
  aid: number; // 项目唯一标识,必传
  token: string; // 项目 token,必传
  // 通用事件上下文
  pid?: string;
  userId?: string;
  deviceId?: string;
  release?: string; // 区分不同版本
  env?: string; // 区分不同环境
  useLocalConfig?: boolean; // 是否只使用本地配置,默认为关
  storageExpires?: number | boolean;// 配置 storage 的过期时间,默认为 90 天
  
  // 采样配置 和 插件配置 的具体配置可在详细配置中查看
  sample?: SampleConfig; // 采样配置
  plugins?: { ... }; // 具体可以查看 【配置插件】

  // 特殊配置
  pluginBundle?: {
    name: string;
    plugins: string[];
  }; // 插件打包加载配置,非定制插件不需要配置
  pluginPathPrefix?:string; // 插件加载路径前缀,调试用(比如 http://localhost:8081/cn/plugins)或加载定制插件用
  domain?: string; // 上报域名,SaaS不需要配置, 私有化部署时需要配置成具体环境的上报域名
}

示例

client('init', {
  aid: 123456, // 你的 aid
  env: 'boe',
  release: '1.0.221'
})

更新配置

更改通用上下文,仅对更新后发送的事件生效。如果需要对所有事件生效,请确保在start之前调用。
client('config', c?: Partial) => WebConfig

// config 可以改动的配置
interface UserConfig {
  pid: string;
  userId: string;
  deviceId: string;
  sessionId:string;
  release: string;
  env: string;
}

// config 获取的配置
interface WebConfig {
  aid: number; // 项目唯一标识,必传
  token: string; // 项目 token,必传
  // 通用事件上下文
  pid: string;
  userId: string;
  deviceId: string;
  sessionId: string; // 区分不同会话
  release: string;// 区分不同版本
  env: string;// 区分不同环境
  useLocalConfig: boolean; // 是否只使用本地配置,默认为关
  storageExpires?: number | boolean; // 配置 storage 的过期时间,默认为 90 天
  
  // 采样配置 和 插件配置 的具体配置可在详细配置中查看
  sample: SampleConfig; // 采样配置
  plugins: { ... }; // 插件配置

  // 特殊配置
  pluginBundle: {
    name: string;
    plugins: string[];
  }; // 插件打包加载配置,非定制插件不需要配置
  pluginPathPrefix:string; // 插件加载路径前缀,调试用(比如 http://localhost:8081/cn/plugins)或加载定制插件用
  domain?: string; // 上报域名,Saas不需要配置, 私有化部署时需要配制成具体环境的上报域名
}

示例

// 更新配置
client('config', {
  userId: 'test_user',
})

// 获取SDK当前配置,如果SDK还未init,则会返回undefined
const config = client('config')

开启上报

client('start')

设置全局上下文

设置自定义维度。context是一个全局维度的上下文,对所有事件生效。更新的context只对之后发生的事件生效。

client("context.set", "key", "value"); // 设置context中的单个key
client("context.merge", { key: "value" }); // 将context 和 传入的对象合并,生成新的context
client("context.delete", "key"); // 删除context中的某个key
client("context.clear"); // 清空context
  • 如果想要给一些初始化的上下文,需要在init之前设置context。因为init的时候会发送一些事件,例如pageview。
  • 如果需要在init之后设置context,又希望能对所有上报生效,可以使用refreshPreStartContext插件。

上报PV

上报一次PV,若pid与当前pid相同则会忽略此次PV。
client('sendPageview',pid: string) => void

示例

client('sendPageview', '/test/pageA')

上报自定义事件

上报一个自定义事件。注意格式,格式不符合的事件将会试图转换,无法转换的事件将会被忽略。具体消费方式可以查看自定义监控
client('sendEvent', data: CustomEventPayload) => void

interface CustomEventPayload {
  /** 自定义事件名称 */
  name: string;
  /** metrics 上报的是可以被度量的值,也就是数值 */
  metrics?: { [key: string]: number };
  /** categories 上报的是分类,维度,用来做筛选,分组 */
  categories?: { [key: string]: string };
}

示例

client('sendEvent', {
  name: 'login_event',
  metrics: {
    login_count: 1,
    login_api_duration: 1000,
    server_timing: 3456,
    login_level: 23,
  },
  categories: {
    where: 'login_page',
  },
})

上报自定义日志

上报一个自定义日志。注意格式,格式不符合的事件将会试图转换,无法转换的事件将会被忽略。
client('sendLog', data: CustomLogPayload) => void

interface CustomLogPayload {
  /** 额外的附加信息, 在上报的时候 number会被分流到metric string会被分流到categories */
  extra?: { [key: string]: string | number }; //
  /** 自定义事件内容,任意字符串,可以是日志或者对象的 JSON 字符串等等 */
  content: string;
  /** 自定义事件级别,默认是 info, 可枚举项 debug | info | warn | error */
  level?: "debug" | "info" | "warn" | "error";
}

示例

client('sendLog', {
  level: 'error',
  content: `user loggedin from ${prev}`,
  extra: {
    where: 'login_page',
  },
})

上报JS错误

client('captureException', error: any, extra?: { [key: string]: string }, react?: ReactInfo) => void

export interface ReactInfo {
  version: string;
  componentStack: string;
}

示例

// 上报一个error
client('captureException', new Error('test error'))

// 上报一个错误信息
client('captureException', 'custom error')

// 上报一个error,同时附带一些错误的上下文
client('captureException', new Error('login error'), { loginId: 'xxxxx' })

上报性能指标

  • 如果是默认集成的指标,例如FP、FCP,可以在Performance插件中关闭上报,通过这种自定义上报的方式上报上去,平台自动消费。
  • 如果不是默认集成的指标,通过这种自定义上报的方式上报上去后,在性能指标管理中注册指标,即可在平台消费。

client('sendCustomPerfMetric', metric: PerformancePayload) => void

interface PerformancePayload {
  /** 指标名称 */
  name: string;
  /** 当前值 */
  value: number;
  /** 性能指标类型, perf => 传统性能, spa => SPA 性能, mf => 微前端性能 */
  type?: string = "perf";
  /** 是否支持 */
  isSupport?: boolean;
  /** 是否是Polyfill */
  isPolyfill?: boolean;
  /** 是否跳出 */
  isBounced?: boolean;
  /** 是否自定义 */
  isCustom?: boolean;
  /** 指标的相关信息 */
  extra?: { [key: string]: string };
}

示例

client('sendCustomPerfMetric', { name: 'fcp', value: 3500 }

销毁实例

调用此方法可以去掉所有监听和副作用,包括hook或者内存对象。当前实例本身还是可用的,所以手动调用API依然可以上报数据。

client('destroy')

上报任意事件

直接上报一个事件,具体格式见上报格式
client('report', ev: ReportEvent) => void

示例

client('report', {
  ev_type: 'pageview',
  payload: {
    source: 'history',
    pid: '/pageB'
  }
})

自定义补充面包屑

面包屑主要在JS错误上报时会携带,如果业务想要自定义一些面包屑,可以使用下面的方式。
client('addBreadcrumb',breadcrumb: Breadcrumb) => void

export interface Breadcrumb {
  /** dom | http */
  type: string;
  /** xpath, keyvalue | url */
  message: string;
  /** ui.click, ui.keypress | post,get */
  category: string;
  /** status: 400 for http */
  data?: { [key: string]: string };
}

示例

client('addBreadcrumb', { type: 'custom', message: 'user login', category: 'webview' })

手动包装Fetch

client('wrapFetch', fetch: typeof window.fetch) => typeof window.fetch | undefined
如果需要手动包装,需要注意以下内容:

  • 需要在init之后执行。因为wrapFetch是动态挂载的,挂载的时机是在init时,所以需要在init后执行。
  • 需要使用npm的接入方式。script接入会先加载主脚本,在这之前所有的调用都只是缓存起来,并没有真正运行,所以提前运行拿到的返回值会是undefined。
  • 需要将fetch插件的autoWrap配置为false。既然选择手动包装,那么就要避免自动包装带来的其他无关请求的监控上报。

示例

import client from '@apmplus/web'

client('init', {
  ...
  plugins: {
    autoWrap: false,
  },
  ...
})

const fetchAfterWrap = client('wrapFetch', window.fetch)

// then, use  fetchAfterWrap to request

手动检测白屏

client('detectBlankScreen')

示例

import client from '@apmplus/web'

client('init', {
  ...
  plugins: {
    blankScreen: {
       // 关闭自动检测,改为下方的手动检测
       autoDetect: false
    },
  },
  ...
})

client('detectBlankScreen')

立即上报数据

默认情况下,在页面关闭时SDK会使用sendBeacon强制发送缓存队列的数据,但是如果在页面关闭时,用户再手动调用某些API上报数据,可能因为时机问题导致漏发,可以使用以下方式强制发送数据:

import client from '@apmplus/web'

// 写在回调里时为了确保SDK已经初始化完成,避免报错
onPageUnload(() => {
    client('on', 'init', () => {
       client.getSender().flush()
    })
})