@capawesome/capacitor-posthog

中文文档
8.6.2发布于 2026/09/11MITTypeScriptESM + CJS零依赖构建来源已验证近 30 天下载 5.7万

Unofficial Capacitor plugin for PostHog SDK on Android, iOS, and Web.

原始使用文档
文档目录55 节
  1. Use Cases
  2. Compatibility
  3. Installation
  4. Android
  5. Configuration
  6. Examples
  7. Demo
  8. Usage
  9. Set up the SDK
  10. Capture events
  11. Track screen views
  12. Identify users
  13. Associate users with a group
  14. Manage super properties
  15. Reset the user
  16. Flush queued events
  17. API
  18. alias(...)
  19. capture(...)
  20. captureException(...)
  21. flush()
  22. getDistinctId()
  23. getFeatureFlag(...)
  24. getFeatureFlagPayload(...)
  25. getSessionId()
  26. group(...)
  27. identify(...)
  28. isFeatureEnabled(...)
  29. isOptOut()
  30. optIn()
  31. optOut()
  32. register(...)
  33. reloadFeatureFlags()
  34. reset()
  35. screen(...)
  36. setPersonProperties(...)
  37. setup(...)
  38. startSessionRecording()
  39. stopSessionRecording()
  40. unregister(...)
  41. Interfaces
  42. Type Aliases
  43. Advanced
  44. Reverse Proxy
  45. FAQ
  46. Do I have to call the setup method before using the plugin?
  47. What is the difference between the apiHost and host options?
  48. How do I use the plugin with a reverse proxy?
  49. How do I enable session replay?
  50. How can users opt out of tracking?
  51. Can I use this plugin with Ionic, React, Vue or Angular?
  52. Related Plugins
  53. Newsletter
  54. Changelog
  55. License

Capacitor PostHog Plugin

Unofficial Capacitor plugin for PostHog.[^1]

Use Cases

The PostHog plugin is typically used to understand how users interact with an app, for example:

  • Product analytics: Capture custom events and screen views to analyze how users move through your app.
  • User identification: Identify users with a distinct ID, assign aliases, and associate their events with groups.
  • Feature flags: Roll out features gradually by checking feature flags and their payloads at runtime.
  • Session replay: Record user sessions to understand usage patterns and debug issues.
  • Error tracking: Capture exceptions manually or automatically to monitor the stability of your app.

Compatibility

Plugin VersionCapacitor VersionStatus
8.x.x>=8.x.xActive support
7.x.x7.x.xDeprecated

Installation

You can use our AI-Assisted Setup to install the plugin. Add the Capawesome Skills to your AI tool using the following command:

npx skills add capawesome-team/skills --skill capacitor-plugins

Then use the following prompt:

 Use the `capacitor-plugins` skill from `capawesome-team/skills` to install the `@capawesome/capacitor-posthog` plugin in my project.

If you prefer Manual Setup, install the plugin by running the following commands and follow the platform-specific instructions below:

npm install @capawesome/capacitor-posthog posthog-js
npx cap sync

Android

Variables

If needed, you can define the following project variable in your app’s variables.gradle file to change the default version of the dependency:

  • $androidxCoreKtxVersion version of androidx.core:core-ktx (default: 1.13.1)
  • $posthogVersion version of com.posthog:posthog-android (default: 3.27.2)

This can be useful if you encounter dependency conflicts with other plugins in your project.

Configuration

PropTypeDescriptionDefaultSince
apiKeystringThe API key of your PostHog project.7.1.0
apiHoststringThe API host of your PostHog instance or reverse proxy.'https://us.i.posthog.com'8.3.0
hoststringThe API host of your PostHog instance. Deprecated alias for apiHost.'https://us.i.posthog.com'7.1.0
uiHoststringThe PostHog UI host used when apiHost points to a reverse proxy. Only available on Web.8.3.0
enableSessionReplaybooleanWhether to enable session recording automatically.false7.3.0
sessionReplayConfigSessionReplayOptionsSession recording configuration options.7.3.0
captureApplicationLifecycleEventsbooleanWhether to capture application lifecycle events.true8.3.0
autoCaptureExceptionsbooleanWhether to automatically capture unhandled exceptions.false8.5.0

Examples

In capacitor.config.json:

{
  "plugins": {
    "Posthog": {
      "apiKey": 'phc_g8wMenebiIQ1pYd5v9Vy7oakn6MczVKIsNG5ZHCspdy',
      "apiHost": 'https://eu.i.posthog.com',
      "host": 'https://eu.i.posthog.com',
      "uiHost": 'https://eu.posthog.com',
      "enableSessionReplay": undefined,
      "sessionReplayConfig": undefined,
      "captureApplicationLifecycleEvents": undefined,
      "autoCaptureExceptions": undefined
    }
  }
}

In capacitor.config.ts:

/// <reference types="@capawesome/capacitor-posthog" />

import { CapacitorConfig } from '@capacitor/cli';

const config: CapacitorConfig = {
  plugins: {
    Posthog: {
      apiKey: 'phc_g8wMenebiIQ1pYd5v9Vy7oakn6MczVKIsNG5ZHCspdy',
      apiHost: 'https://eu.i.posthog.com',
      host: 'https://eu.i.posthog.com',
      uiHost: 'https://eu.posthog.com',
      enableSessionReplay: undefined,
      sessionReplayConfig: undefined,
      captureApplicationLifecycleEvents: undefined,
      autoCaptureExceptions: undefined,
    },
  },
};

export default config;

Demo

A working example can be found here: robingenz/capacitor-plugin-demo

Usage

The following examples show how to set up the SDK, capture events, track screen views, identify users, associate users with a group, manage super properties, reset the user, and flush queued events.

Set up the SDK

Call setup(...) before any other method. Alternatively, on Android and iOS, you can configure the plugin in your Capacitor configuration file (see Configuration); in that case, you must not call this method:

import { Posthog } from '@capawesome/capacitor-posthog';

const setup = async () => {
  await Posthog.setup({
    apiKey: 'YOUR_API_KEY',
    apiHost: 'https://eu.i.posthog.com',
  });
};

Capture events

Capture a custom event with optional properties:

import { Posthog } from '@capawesome/capacitor-posthog';

const capture = async () => {
  await Posthog.capture({
    event: 'event',
    properties: {
      key: 'value',
    },
  });
};

Track screen views

Send a screen event with the title of the screen. Only available on Android and iOS:

import { Posthog } from '@capawesome/capacitor-posthog';

const screen = async () => {
  await Posthog.screen({
    screenTitle: 'screen',
    properties: {
      key: 'value',
    },
  });
};

Identify users

Identify the current user with a distinct ID and set person properties. You can also assign another distinct ID to the current user using alias(...):

import { Posthog } from '@capawesome/capacitor-posthog';

const identify = async () => {
  await Posthog.identify({
    distinctId: 'distinct-id',
    userProperties: {
      key: 'value',
    },
  });
};

const alias = async () => {
  await Posthog.alias({
    alias: 'new-distinct-id',
  });
};

Associate users with a group

Associate the events of the current user with a group, for example a company or a team:

import { Posthog } from '@capawesome/capacitor-posthog';

const group = async () => {
  await Posthog.group({
    type: 'group',
    key: 'key',
    groupProperties: {
      key: 'value',
    },
  });
};

Manage super properties

Register a super property that is sent with every event, and unregister it when it is no longer needed:

import { Posthog } from '@capawesome/capacitor-posthog';

const register = async () => {
  await Posthog.register({
    key: 'super-property',
    value: 'super-value',
  });
};

const unregister = async () => {
  await Posthog.unregister({
    key: 'super-property',
  });
};

Reset the user

Reset the current user's ID and anonymous ID, for example after a logout:

import { Posthog } from '@capawesome/capacitor-posthog';

const reset = async () => {
  await Posthog.reset();
};

Flush queued events

Manually flush all events in the queue. Only available on Android and iOS:

import { Posthog } from '@capawesome/capacitor-posthog';

const flush = async () => {
  await Posthog.flush();
};

API

alias(...)

alias(options: AliasOptions) => Promise<void>

Assign another distinct ID to the current user.

ParamType
optionsAliasOptions

Since: 6.0.0


capture(...)

capture(options: CaptureOptions) => Promise<void>

Capture an event.

ParamType
optionsCaptureOptions

Since: 6.0.0


captureException(...)

captureException(options: CaptureExceptionOptions) => Promise<void>

Capture an exception.

ParamType
optionsCaptureExceptionOptions

Since: 8.5.0


flush()

flush() => Promise<void>

Flush all events in the queue.

Only available on Android and iOS.

Since: 6.0.0


getDistinctId()

getDistinctId() => Promise<GetDistinctIdResult>

Get the current distinct ID.

Returns: Promise<GetDistinctIdResult>

Since: 8.2.0


getFeatureFlag(...)

getFeatureFlag(options: GetFeatureFlagOptions) => Promise<GetFeatureFlagResult>

Get the value of a feature flag.

ParamType
optionsGetFeatureFlagOptions

Returns: Promise<GetFeatureFlagResult>

Since: 7.0.0


getFeatureFlagPayload(...)

getFeatureFlagPayload(options: GetFeatureFlagPayloadOptions) => Promise<GetFeatureFlagPayloadResult>

Get the payload of a feature flag.

ParamType
optionsGetFeatureFlagPayloadOptions

Returns: Promise<GetFeatureFlagPayloadResult>

Since: 7.1.0


getSessionId()

getSessionId() => Promise<GetSessionIdResult>

Get the current session ID.

Returns: Promise<GetSessionIdResult>

Since: 8.6.0


group(...)

group(options: GroupOptions) => Promise<void>

Associate the events for that user with a group.

ParamType
optionsGroupOptions

Since: 6.0.0


identify(...)

identify(options: IdentifyOptions) => Promise<void>

Identify the current user.

ParamType
optionsIdentifyOptions

Since: 6.0.0


isFeatureEnabled(...)

isFeatureEnabled(options: IsFeatureEnabledOptions) => Promise<IsFeatureEnabledResult>

Check if a feature flag is enabled.

ParamType
optionsIsFeatureEnabledOptions

Returns: Promise<IsFeatureEnabledResult>

Since: 7.0.0


isOptOut()

isOptOut() => Promise<IsOptOutResult>

Check if the user has opted out of capturing.

Returns: Promise<IsOptOutResult>

Since: 8.1.0


optIn()

optIn() => Promise<void>

Opt in to event capturing.

Since: 8.1.0


optOut()

optOut() => Promise<void>

Opt out of event capturing.

On Web with cookielessMode: 'on_reject': switches to cookieless anonymous tracking. On iOS/Android: stops all event capturing entirely.

Since: 8.1.0


register(...)

register(options: RegisterOptions) => Promise<void>

Register a new super property. This property will be sent with every event.

ParamType
optionsRegisterOptions

Since: 6.0.0


reloadFeatureFlags()

reloadFeatureFlags() => Promise<void>

Reload the feature flags.

Since: 7.0.0


reset()

reset() => Promise<void>

Reset the current user's ID and anonymous ID.

Since: 6.0.0


screen(...)

screen(options: ScreenOptions) => Promise<void>

Send a screen event.

Only available on Android and iOS.

ParamType
optionsScreenOptions

Since: 6.0.0


setPersonProperties(...)

setPersonProperties(options: SetPersonPropertiesOptions) => Promise<void>

Set properties on the person associated with the current user.

ParamType
optionsSetPersonPropertiesOptions

Since: 8.6.0


setup(...)

setup(options: SetupOptions) => Promise<void>

Setup the PostHog SDK with the provided options.

Attention: This method should be called before any other method. Alternatively, on Android and iOS, you can configure this plugin in your Capacitor Configuration file. In this case, you must not call this method.

ParamType
optionsSetupOptions

Since: 6.0.0


startSessionRecording()

startSessionRecording() => Promise<void>

Start session recording.

Since: 7.3.0


stopSessionRecording()

stopSessionRecording() => Promise<void>

Stop session recording.

Since: 7.3.0


unregister(...)

unregister(options: UnregisterOptions) => Promise<void>

Remove a super property.

ParamType
optionsUnregisterOptions

Since: 6.0.0


Interfaces

AliasOptions

PropTypeDescriptionSince
aliasstringThe new distinct ID to assign to the current user.6.0.0

CaptureOptions

PropTypeDescriptionSince
eventstringThe name of the event to capture.6.0.0
propertiesRecord<string, any>The properties to send with the event.6.0.0

CaptureExceptionOptions

PropTypeDescriptionDefaultSince
messagestringThe message of the exception.8.5.0
namestringThe name of the exception. Used as the exception type for grouping.'Error'8.5.0
stacktraceStackFrame[]The stack trace of the exception. Can be generated from an Error using stacktrace.js.8.5.0
propertiesRecord<string, any>The properties to send with the exception.8.5.0

StackFrame

PropTypeDescriptionSince
functionNamestringThe name of the function.8.5.0
fileNamestringThe name of the file.8.5.0
lineNumbernumberThe line number within the file.8.5.0
columnNumbernumberThe column number within the file.8.5.0

GetDistinctIdResult

PropTypeDescriptionSince
distinctIdstringThe current distinct ID.8.2.0

GetFeatureFlagResult

PropTypeDescriptionSince
valuestring | boolean | nullThe value of the feature flag. If the feature flag does not exist, the value will be null.7.0.0

GetFeatureFlagOptions

PropTypeDescriptionSince
keystringThe key of the feature flag.7.0.0

GetFeatureFlagPayloadResult

PropTypeDescriptionSince
valueJsonTypeThe value of the feature flag payload.7.1.0

GetFeatureFlagPayloadOptions

PropTypeDescriptionSince
keystringThe key of the feature flag.7.1.0

GetSessionIdResult

PropTypeDescriptionSince
sessionIdstring | nullThe current session ID. If no session is active, the value will be null.8.6.0

GroupOptions

PropTypeDescriptionSince
typestringThe group type.6.0.0
keystringThe group key.6.0.0
groupPropertiesRecord<string, any>The properties to send with the group event.6.0.0

IdentifyOptions

PropTypeDescriptionSince
distinctIdstringThe distinct ID of the user.6.0.0
userPropertiesRecord<string, any>The person properties to set.6.0.0

IsFeatureEnabledResult

PropTypeDescriptionSince
enabledbooleanWhether the feature flag is enabled. If the feature flag does not exist, the value will be false.7.0.0

IsFeatureEnabledOptions

PropTypeDescriptionSince
keystringThe key of the feature flag.7.0.0

IsOptOutResult

PropTypeDescriptionSince
optedOutbooleanWhether the user has opted out of capturing.8.1.0

RegisterOptions

PropTypeDescriptionSince
keystringThe name of the super property.6.0.0
valueanyThe value of the super property.6.0.0

ScreenOptions

PropTypeDescriptionSince
screenTitlestringThe name of the screen.6.0.0
propertiesRecord<string, any>The properties to send with the screen event.6.0.0

SetPersonPropertiesOptions

PropTypeDescriptionSince
propertiesRecord<string, any>The person properties to set.8.6.0
setOncePropertiesRecord<string, any>The person properties to set only once. Existing values will not be overwritten.8.6.0

SetupOptions

PropTypeDescriptionDefaultSince
apiKeystringThe API key of your PostHog project.6.0.0
apiHoststringThe API host of your PostHog instance or reverse proxy. If both apiHost and host are provided, apiHost takes precedence.'https://us.i.posthog.com'8.3.0
hoststringThe API host of your PostHog instance. Deprecated alias for apiHost.'https://us.i.posthog.com'6.0.0
uiHoststringThe PostHog UI host used when apiHost points to a reverse proxy. Only available on Web.8.3.0
cookielessMode'always' | 'on_reject'Cookieless tracking mode. - 'always': Always use cookieless tracking with server-side anonymous hash. - 'on_reject': Normal tracking until optOut() is called, then switches to cookieless. Only available on Web. Requires cookieless mode to be enabled in PostHog project settings.8.1.0
enableSessionReplaybooleanWhether to enable session recording automatically.false7.3.0
optOutbooleanWhether to opt out of capturing by default. User must call optIn() to enable capturing.false8.1.0
sessionReplayConfigSessionReplayOptionsSession replay configuration options.7.3.0
captureApplicationLifecycleEventsbooleanWhether to capture application lifecycle events. Only available on iOS and Android.true8.3.0
autoCaptureExceptionsbooleanWhether to automatically capture unhandled exceptions.false8.5.0
preloadFeatureFlagsbooleanWhether to preload feature flags on startup. Only available on Android and iOS.true8.6.0
surveysbooleanWhether to enable surveys. Only available on iOS and Web.true8.6.0
webConfigRecord<string, any>Additional posthog-js configuration options that are merged into the configuration passed to posthog.init. Options set here take precedence over the other setup options. Only available on Web.8.6.0

SessionReplayOptions

PropTypeDescriptionDefaultSince
screenshotModebooleanEnable screenshot mode for session recordings. WARNING: This may capture sensitive information.false7.3.0
maskAllTextInputsbooleanMask all text input fields in session recordings.true7.3.0
maskAllImagesbooleanMask all images in session recordings.true7.3.0
maskAllSandboxedViewsbooleanMask all sandboxed system views (iOS-specific).true7.3.0
captureNetworkTelemetrybooleanCapture network telemetry in session recordings.false7.3.0
debouncerDelaynumberDebounce delay for session recording snapshots (in seconds).1.07.3.0

UnregisterOptions

PropTypeDescriptionSince
keystringThe name of the super property to remove.6.0.0

Type Aliases

JsonType

string | number | boolean | null | { [key: string]: JsonType; } | JsonType[]

Advanced

Reverse Proxy

For PostHog managed reverse proxy, set apiHost to your proxy URL and uiHost to your PostHog app host (https://us.posthog.com or https://eu.posthog.com). host remains supported as a deprecated alias for apiHost. uiHost is only available on Web.

FAQ

Do I have to call the setup method before using the plugin?

Yes, the setup(...) method should be called before any other method. Alternatively, on Android and iOS, you can configure the plugin in your Capacitor configuration file (see Configuration). In that case, you must not call the setup(...) method.

What is the difference between the apiHost and host options?

The host option is a deprecated alias for apiHost. Both point to the API host of your PostHog instance or reverse proxy. If both options are provided, apiHost takes precedence, so new projects should only use apiHost.

How do I use the plugin with a reverse proxy?

Set the apiHost option to your proxy URL and the uiHost option to your PostHog app host, such as https://us.posthog.com or https://eu.posthog.com. Note that uiHost is only available on Web. See the Reverse Proxy section for more details.

How do I enable session replay?

Set the enableSessionReplay option to true in the setup(...) method or in your Capacitor configuration file, and fine-tune the recording behavior with the sessionReplayConfig option. You can also start and stop recording manually using the startSessionRecording() and stopSessionRecording() methods.

How can users opt out of tracking?

Call the optOut() method to stop event capturing and the optIn() method to re-enable it. You can check the current state with isOptOut() or opt users out by default with the optOut setup option. On Web with cookielessMode: 'on_reject', opting out switches to cookieless anonymous tracking instead of stopping capturing entirely.

Can I use this plugin with Ionic, React, Vue or Angular?

Yes, the plugin is framework-agnostic. It works in any Capacitor app regardless of the web framework, including Ionic with Angular, React, or Vue, as well as plain JavaScript projects.

  • Analytics: Unofficial Capacitor plugin for Firebase Analytics.
  • Crisp: Unofficial Capacitor plugin for the Crisp live chat and customer support platform.
  • Formbricks: Unofficial Capacitor plugin for Formbricks to run in-app surveys.
  • Grafana Faro: Unofficial Capacitor plugin for Grafana Faro to monitor your app.
  • TikTok App Events: Unofficial Capacitor plugin for the TikTok App Events SDK.

Newsletter

Stay up to date with the latest news and updates about the Capawesome, Capacitor, and Ionic ecosystem by subscribing to our Capawesome Newsletter.

Changelog

See CHANGELOG.md.

License

See LICENSE.

[^1]: This project is not affiliated with, endorsed by, sponsored by, or approved by PostHog, Inc. or any of their affiliates or subsidiaries.

版本与发布记录

@capawesome/capacitor-posthog 共发布 22 个版本,首次发布于 2024/09/06;过去 12 个月发布了 16 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
8.6.2latest2026/09/111 个月前
8.6.12026/09/022 个月前
8.6.02026/08/282 个月前
8.5.12026/08/132 个月前
8.5.02026/06/224 个月前
8.4.22026/04/256 个月前

其他发布通道:dev → 7.0.0-dev.1765885034。

关于 @capawesome/capacitor-posthog 的常见问题

@capawesome/capacitor-posthog 是什么?

Unofficial Capacitor plugin for PostHog SDK on Android, iOS, and Web.

如何安装 @capawesome/capacitor-posthog?

在项目目录运行 npm install @capawesome/capacitor-posthog,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@capacitor/core(>=8.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@capawesome/capacitor-posthog 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@capawesome/capacitor-posthog 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@capawesome/capacitor-posthog 可以商用吗?

@capawesome/capacitor-posthog 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@capawesome/capacitor-posthog 的下载量有多少?

根据 npm 官方下载统计,@capawesome/capacitor-posthog 在 2026/10/09 – 2026/11/07 这 30 天内被下载 57,296 次,日均约 1,910 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@capawesome/capacitor-posthog 还在维护吗?

最新版本 8.6.2 发布于 2026/09/11(1 个月前);至今共发布 22 个版本,其中过去 12 个月发布了 16 个;首次发布于 2024/09/06。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。