Browser SDK 2リファレンス

このリファレンスでは、@amplitude/analytics-browserのすべてのパブリックエクスポートと、init()に渡すことができるすべてのオプションをバージョン2.48.1と照合して検証したことを文書化しています。 スクリプトローダーを使用すると、同じメンバーがグローバルamplitudeオブジェクトで使用できます。 オプションについては、設定オプションを参照してください。 機能が追加または変更されたリリースを確認するには、Browser SDK 2のリリースノートを参照してください。

ts
import * as amplitude from "@amplitude/analytics-browser";

トップレベルの関数はデフォルトのインスタンスで動作します。 createInstance()の各インスタンスには同じメソッドがあります。

戻り値

非同期動作を実行するメソッドは、AmplitudeReturn<T>を返します。これは、1つのプロパティを持つオブジェクトですpromise。 Awaitpromise(待機)であり、戻り値自体ではありません。

ts
const result = await amplitude.track("Song Played").promise; // correct
const wrapper = await amplitude.track("Song Played"); // returns { promise }, not a Result

アップロードの試行が完了すると、トラッキングメソッドはResult~に解決されます:

すべてのコードとメッセージについては、「アップロード結果の読み取り」を参照してください。

完了する前にinit()行われた呼び出しはキューで待機し、その後、順次実行されます。それらのPromiseは、処理が終了し、アップロードが完了したinit()後に解決されます。

セットアップ

init

インスタンスを初期化します。 インスタンスごとに1回呼び出してください。終了後に再びを呼び出すと、追加したプラグインを含むすべてのプラグインが破棄され、最初からやり直されます。

ts
init(apiKey: string, options?: BrowserOptions): AmplitudeReturn<void>
init(apiKey: string, userId?: string, options?: BrowserOptions): AmplitudeReturn<void>

promiseSDKがリモート設定を取得し、プラグインをインストールして、キューに入れられた呼び出しを実行した後、解決されます。

ts
await amplitude.init("YOUR_API_KEY", "user-12345", {
  serverZone: "EU",
}).promise;

createInstance

独自の設定、ID、キュー、プラグインを使用して独立したインスタンスを作成します。 この設定を使用して、複数のプロジェクトにデータを送信します。

ts
createInstance(): BrowserClient
ts
const secondary = amplitude.createInstance();
secondary.init("OTHER_API_KEY", { instanceName: "secondary" });

スクリプトローダーを使用すると、amplitude.createInstance(name)インスタンスも登録されるため、SDKがロードされる前に行われた呼び出しはname、そのインスタンスに到達します。

追加する

プラグインを追加します。setup()インスタンス上で実行済みの場合はinit()直ちに実行され、それ以外の場合は期間中にinit()実行されます。SDKは、すでに追加されているプラグインと一致するプラグインをスキップし、警告を記録しますname。

ts
add(plugin: Plugin): AmplitudeReturn<void>
ts
await amplitude.add({
  name: "add-app-section",
  execute: async (event) => {
    event.event_properties = { ...event.event_properties, section: "checkout" };
    return event;
  },
}).promise;

プラグインのコントラクトについては、Pluginを参照してください。

削除する

プラグインを名前で削除し、そのteardown()メソッドを呼び出します。

ts
remove(pluginName: string): AmplitudeReturn<void>
ts
amplitude.remove("add-app-section");

setTransport

今後のアップロード用に HTTP APIを変更します。

ts
setTransport(transport: "fetch" | "xhr" | "beacon" | TransportOptions): void
ts
window.addEventListener("pagehide", () => {
  amplitude.setTransport("beacon");
  amplitude.flush();
});

フラッシュ

キューに入ったすべてのイベントをアップロードします。 手動でのフラッシュは、失敗したアップロードを再試行しません。

ts
flush(): AmplitudeReturn<void>
ts
await amplitude.flush().promise;

トラッキング

トラック

カスタムイベントを送信します。logEvent()これは同じシグネチャを持つエイリアスです。

ts
track(eventInput: string | BaseEvent, eventProperties?: Record<string, any>, eventOptions?: EventOptions): AmplitudeReturn<Result>
logEvent(eventInput: string | BaseEvent, eventProperties?: Record<string, any>, eventOptions?: EventOptions): AmplitudeReturn<Result>
ts
amplitude.track(
  "Song Played",
  { title: "Here Comes the Sun" },
  { time: Date.now() },
);

identify

ユーザープロパティを更新する$identifyイベントを送信します。user_idが または device_idを含むeventOptions場合、SDK はそれを使用して setUserId()または setDeviceId()を呼び出します。

ts
identify(identify: Identify, eventOptions?: EventOptions): AmplitudeReturn<Result>
ts
amplitude.identify(new amplitude.Identify().set("plan", "pro"));

setGroup

groupssetを使用して$identifyイベントを送信することにより、現在のユーザーをグループに割り当てます。

ts
setGroup(groupType: string, groupName: string | string[], eventOptions?: EventOptions): AmplitudeReturn<Result>
ts
amplitude.setGroup("company", "Acme Inc");

groupIdentify

1つのグループのプロパティを更新する$groupidentifyイベントを送信します。 更新は、その時点以降のイベントにのみ適用されます。

ts
groupIdentify(groupType: string, groupName: string | string[], identify: Identify, eventOptions?: EventOptions): AmplitudeReturn<Result>
ts
amplitude.groupIdentify(
  "company",
  "Acme Inc",
  new amplitude.Identify().set("seats", 250),
);

収益

Revenueオブジェクトから構築されたrevenue_amountイベントを送信します。

ts
revenue(revenue: Revenue, eventOptions?: EventOptions): AmplitudeReturn<Result>
ts
amplitude.revenue(
  new amplitude.Revenue().setProductId("pro-annual").setPrice(99.99),
);

trackVideo

試験的機能。<video>要素または player.js 埋め込みプレイヤーから、Video Content StartedイベントとVideo Content Stoppedイベントをトラッキングします。Browser SDK 2.39.0以降が必要です。

ts
trackVideo(amplitude: BrowserClient, video: HTMLVideoElement | EmbeddedVideoPlayer, options?: VideoCaptureOptions): (() => void) | Error

追跡を停止する関数を返します。SDKが添付できない場合はErrorを返します。

ts
const stop = amplitude.trackVideo(amplitude, document.querySelector("video")!);

アイデンティティ

getUserIdとsetUserId

今後のイベント用にユーザーIDを読み取るか設定します。setUserId(undefined)クリアします。

ts
getUserId(): string | undefined
setUserId(userId: string | undefined): void
ts
amplitude.setUserId("user-12345");

getDeviceIdとsetDeviceId

今後のイベント用にデバイスIDを読み取るか設定します。

ts
getDeviceId(): string | undefined
setDeviceId(deviceId: string): void
ts
amplitude.setDeviceId("2f9d6a1e-4b7c-4f0e-9a51-0c3e8b7d5a12");

リセット

ユーザーIDをクリアし、新しいデバイスIDを生成します。ユーザーがログアウトしたときに使用します。新しいセッションを開始することはありません。

ts
reset(): void
ts
amplitude.reset();

getIdentityとsetIdentity

デバイスID、ユーザーID、ユーザープロパティを一緒に読み取るか更新します。setIdentity()を受け取るuserPropertiesと、各キーを$set で設定する $identifyイベントが送信されます。userProperties は、このページ読み込みから設定されたプロパティのみを保持します。getIdentity() は Browser SDK 2.18.0 以降を必要とし、setIdentity() は 2.35.0 以降を必要とします。

ts
getIdentity(): { deviceId?: string; userId?: string; userProperties?: Record<string, any> }
setIdentity(identity: { deviceId?: string; userId?: string; userProperties?: Record<string, any> }): void
ts
amplitude.setIdentity({
  userId: "user-12345",
  userProperties: { plan: "pro" },
});

セッション

getSessionIdとsetSessionId

現在のセッションIDを読み取るか、現在のセッションを終了し、指定されたIDを使用してセッションを開始します。 Unixタイムスタンプをミリ秒単位で渡します。 オプトアウトされたインスタンスはIDを保存し、オプトアウトがオフになったときにセッションを開始します。

ts
getSessionId(): number | undefined
setSessionId(sessionId: number): void
ts
amplitude.setSessionId(Date.now());

extendSession

イベントを送信することなく、セッションを現在アクティブなものとしてマークします。

ts
extendSession(): void
ts
amplitude.extendSession();

プライバシー

getOptOutとsetOptOut

オプトアウトの読み取りまたは設定を行います。オプトアウトが有効な間true、SDK はすべてのイベントをドロップします。この値はIDストレージに保持されます。getOptOut() は Browser SDK 2.18.0 以降を必要とします。

ts
getOptOut(): boolean | undefined
setOptOut(optOut: boolean): void
ts
amplitude.setOptOut(true);

Identify

Identify は、identify() 、groupIdentify() 、およびidentify init オプションに対するユーザープロパティまたはグループプロパティ操作を構築します。各メソッドは同じオブジェクトを返すため、メソッドチェーンが可能です。各プロパティは、オブジェクトごとに1つの操作のみを実行できます。 SDKは、同じプロパティに対するその後の操作と、それ以降のすべての操作を無視しますclearAll()。

ts
const identify = new amplitude.Identify();

値は、文字列、数値、ブール値、配列、またはそれらの型のオブジェクトを受け入れます。

収益

revenue_amount イベントのプロパティを構築します。Revenue 各セッターは同じオブジェクトを返します。

ts
const revenue = new amplitude.Revenue();

プラグイン

プラグインは、SDKがすべてのイベントに対して実行するオブジェクトです。それをadd()に渡します。

各イベントについて、SDKはすべてのBeforeプラグインを実行し、次にすべてのenrichmentプラグイン、最後にすべての送信先プラグインを実行します。同じタイプのプラグインは、追加した順序で実行されます。 ~init()の前に追加されたプラグインは、組み込みの autocapture プラグインより先にインストールされるため、最初に実行されます。

ts
const lowercaseUserId: amplitude.Types.BeforePlugin = {
  name: "lowercase-user-id",
  type: "before",
  execute: async (event) => {
    if (event.user_id) event.user_id = event.user_id.toLowerCase();
    return event;
  },
};
amplitude.add(lowercaseUserId);

イベントを独自の endpoint に転送する送信先プラグイン:

ts
const forwardToWarehouse = (
  url: string,
): amplitude.Types.DestinationPlugin => ({
  name: "forward-to-warehouse",
  type: "destination",
  execute: async (event) => {
    const response = await fetch(url, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(event),
    });
    return { event, code: response.status, message: response.statusText };
  },
});
amplitude.add(forwardToWarehouse("https://collect.example.com/events"));

Amplitudeは、Page URL enrichmentやCustom enrichmentなどの既成のプラグインを公開しています。 詳細については、SDKプラグインを参照してください。

種類

amplitude.Types TypeScript の型と定数をエクスポートします(以下を含む):

連携エクスポート

これらのエクスポートは、他のAmplitudeパッケージにも存在します。 ほとんどのアプリでは、これらの設定は必要ありません。

設定オプション

このセクションでは、BrowserOptionsBrowser SDK 2.48.1時点におけるinit()、渡される設定オブジェクトのすべてのオプションを記載します。すべてのオプションはオプションです。 非推奨とマークされたオプションは引き続き機能します。

ts
amplitude.init(apiKey: string, options?: BrowserOptions);
amplitude.init(apiKey: string, userId?: string, options?: BrowserOptions);

Identityとセッション

クッキーのオプション

SDKは次のCookieを設定します:

データ収集

Delivery

トランスポートオプション

リモート設定と診断

カスタム実装は、すべてのILoggerメソッドloggerProviderを実装する必要があります。この例では、SDKエラーを独自のエラーレポートに転送し、デフォルトのコンソール出力を保持します。

ts
class ErrorReportingLogger implements amplitude.Types.ILogger {
  private level = amplitude.Types.LogLevel.Warn;
  enable(logLevel: amplitude.Types.LogLevel) {
    this.level = logLevel;
  }
  disable() {
    this.level = amplitude.Types.LogLevel.None;
  }
  log(...args: any[]) {
    if (this.level >= amplitude.Types.LogLevel.Verbose) console.log(...args);
  }
  warn(...args: any[]) {
    if (this.level >= amplitude.Types.LogLevel.Warn) console.warn(...args);
  }
  error(...args: any[]) {
    reportError(args.join(" ")); // Your error reporting, at every log level.
    if (this.level >= amplitude.Types.LogLevel.Error) console.error(...args);
  }
  debug(...args: any[]) {
    if (this.level >= amplitude.Types.LogLevel.Debug) console.log(...args);
  }
}
amplitude.init("YOUR_API_KEY", { loggerProvider: new ErrorReportingLogger() });

自動キャプチャオプション

autocapture は、false、true、またはこれらのキーを持つオブジェクトを受け入れます。 動作と例については、Autocaptureを参照してください。

performanceTracking を除くすべてのキーが有効になります。autocapture: true Chrome拡張機能では、default-onキーは設定されていない限りオフです。 デフォルトは2.42.1で変更されました。

AttributionOptions

PageTrackingOptions

FormInteractionsOptions

ElementInteractionsOptions

FrustrationInteractionsOptions

ネットワークトラッキングオプション

それぞれは以下NetworkCaptureRuleを受け入れます:

Amplitudeは、BrowserOptionsの最上位レベルでnetworkTrackingOptions廃止されました。autocapture.networkTrackingを使用します。

WebVitalsOptions

PerformanceTrackingOptions

これは役に立ちましたか?

For AI agents: a documentation index is available at /docs/llms.txt. Append .md to any page URL for markdown, or send Accept: text/markdown.

このページでは