On this page

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.

Javascript SDK から Browser SDK 2.0 への移行

Amplitude Browser SDK 2.0(@amplitude/analytics-browser@2+)は、次の機能を提供します。

  • プラグインアーキテクチャ。
  • 組み込み型定義。
  • フロントエンドフレームワークに対する幅広いサポート。
  • 自動キャプチャ
  • マーケティングアトリビューション追跡の改善。
  • 他のAmplitude SDKとの間で、プラットフォーム間で同一のインターフェースを実現。

Browser SDK 2.0はamplitude-jsと下位互換性がありません。

@amplitude/analytics-browser@2+に移行するには、依存関係とインストルメンテーションを更新してください。

破壊的変更

@amplitude/analytics-browser@2+へ移行すると、実装環境でWebアトリビューションに影響が生じる可能性があります。アップグレードする前に、セッション中にアトリビューションを実行するかどうかを選択してください。 アップグレード後、アトリビューションはセッション中に発生するようになり、設定することはできません。

どちらのバージョンでも、アトリビューションは初期化時に発生することがあります。

クッキーの移行 Browser SDK 2.0 は、JavaScript SDK バージョン 6.0.0 以降から クッキー を自動的に移行します。

  • JavaScript SDK 6.0.0以降の古いクッキー名はAMP_{first 6 digit of api key}
  • Browser SDK 2以降の新しいクッキー名はAMP_{first 10 digit of api key}

JavaScript SDK バージョン 6.0.0 より前から移行するには、手動で クッキー の移行が必要です。

クッキーを手動で移行する方法:

  1. 古い クッキー から値を読み取ります。
  2. これらの値をSDK設定でamplitude.init()に渡します。
ts
this.init("API_KEY", {
  deviceId: "device_id",
  userId: "user_id",
});

用語

  • amplitude-js:Maintenance Browser SDK。
  • @amplitude/analytics-browser@2+:Browser SDK 2.0。

依存関係

スニペットをインストールするには、プロジェクトのスニペットローダーを更新してください。

Nodeプロジェクトの場合、package.jsonで依存関係リストを更新してください。

{
  "dependencies": {
    "amplitude-js": "^8"
  }
}

インスツルメンテーション

ブラウザSDK 2.0はイベントを計測するためのAPIを提供します。Browser SDK 2.0 に移行するには、いくつかの呼び出しを更新します。 次のセクションでは、どのコールが変更されたかについて詳しく説明します。

初期化

Browser SDK 2.0ではgetInstance()が削除されています。SDKを初期化するには、同じパラメータを使用してinit()を呼び出します。configオブジェクトは異なる形状を使用します。設定を参照してください。

import amplitude from "amplitude-js";
amplitude.getInstance().init(API_KEY, OPTIONAL_USER_ID, config);

設定

イベントの追跡

メンテナンスBrowser SDKでは、イベントペイロード内の特定のプロパティをオーバーライドするための、logEventWithTimestamplogEventWithGroupsなど、いくつかのlogEventAPIが提供されています。@amplitude/analytics-browser@2+では、代わりに統合trackAPIを使用してください。

logEvent()

logEvent()APIはtrack()にマップされます。

const eventType = "Button Clicked";
const eventProperties = {
  type: "primary",
};
amplitude.getInstance().logEvent(eventType, eventProperties);

logEventWithTimestamp()

logEventWithTimestamp()APIはtrack()にマップされます。

const eventType = "Button Clicked";
const eventProperties = {
  type: "primary",
};
const timestamp = Date.now();
amplitude
  .getInstance()
  .logEventWithTimestamp(eventType, eventProperties, timestamp);

logEventWithGroups()

logEventWithGroups()APIはtrack()にマップされます。

const eventType = "Button Clicked";
const eventProperties = {
  type: "primary",
};
const groups = {
  orgId: "12345",
};
amplitude.getInstance().logEventWithGroups(eventType, eventProperties, groups);

sendEvents()

sendEvents()APIはflush()にマップされます。

amplitude.getInstance().sendEvents();

ユーザープロパティを設定する

ユーザープロパティを設定するためのAPIは同じですが、getInstance()は必要なくなりました。次のコードスニペットは、ユーザープロパティの API を移行する方法を示しています。

setUserId()

識別子の最小長メンテナンス

SDKは古いSDKエンドポイント(api2.amplitude.com)を使用しており、このエンドポイントはdeviceIduserIdに長さ制限を課していません。最新のSDKはAmplitudeのHTTP V2 API(api2.amplitude.com/2/httpapi)を使用しており、デフォルトでは識別子が5文字以上である必要があります。最新のSDKに移行する際には、5文字未満の識別子を許可している場合は、config.minIdLengthをより小さい値に設定してください。

getInstance()を呼び出さずにamplitudeを呼び出す場合は、userIdを設定します。

const userId = "1";
amplitude.getInstance().setUserId(userId);

setDeviceId()

識別子の最小長メンテナンス

SDKは古いSDKエンドポイント(api2.amplitude.com)を使用しており、このエンドポイントはdeviceIduserIdに長さ制限を課していません。最新のSDKはAmplitudeのHTTP V2 API(api2.amplitude.com/2/httpapi)を使用しており、デフォルトでは識別子が5文字以上である必要があります。最新のSDKに移行する際には、5文字未満の識別子を許可している場合は、config.minIdLengthをより小さい値に設定してください。

getInstance()を呼び出さずにamplitudeを呼び出す場合は、deviceIdを設定します。

const deviceId = "1";
amplitude.getInstance().setDeviceId(deviceId);

setSessionId()

getInstance()を呼び出さずにamplitudeを呼び出す場合は、sessionIdを設定します。

const sessionId = Date.now();
amplitude.getInstance().setSessionId(sessionId);

clearUserProperties()

Browser SDK 2.0では、このclearUserPropertiesAPIが削除されています。ユーザープロパティを削除するには、統合されたidentifyAPIを使用してください。

amplitude.getInstance().clearUserProperties();

setUserProperties()

Browser SDK 2.0では、このsetUserPropertiesAPIが削除されています。ユーザープロパティを追加するには、統合されたidentifyAPIを使用してください。

amplitude.getInstance().setUserProperties({
  membership, "paid",
  payment, "bank",
})

identify()

getInstance()を呼び出さずにamplitudeでidentifyを呼び出します。

const identify = new amplitude.Identify();
identify.set("membership", "paid");
amplitude.getInstance().identify(identify);

グループプロパティを設定する

groupIdentify()

getInstance()を呼び出さずにamplitudeでidentifyを呼び出します。

const identify = new amplitude.Identify();
identify.set("membership", "paid");
amplitude.getInstance().groupIdentify(identify);

収益の追跡

logRevenueV2()

getInstance()を呼び出さずに、amplituderevenue()APIを使用して収益を追跡します。

const revenue = new amplitude.Revenue();
revenue.setProductId("productId").setPrice(10);
amplitude.getInstance().logRevenueV2(revenue);

パターン

プラグイン

amplitude-jsでは、config.languageconfig.libraryconfig.platformを構成することで、これらの特定のフィールドのイベントペイロードを変更できます。@amplitude/analytics-browser@2+はこれらの設定をサポートしていませんが、新しいブラウザSDKにプラグインを追加してイベントペイロードを強化できます。

ts
import {
  BrowserConfig,
  EnrichmentPlugin,
  Event,
  PluginType,
} from "@amplitude/analytics-types";
export class LibraryModifierPlugin implements EnrichmentPlugin {
  name = "library-modifier";
  type = PluginType.ENRICHMENT as const;
  /**
   * setup() is called on plugin installation
   * example: client.add(new LibraryModifierPlugin());
   */
  setup(config: BrowserConfig): Promise<undefined> {
    this.config = config;
  }
  /**
   * execute() is called on each event instrumented
   * example: client.track('New Event');
   */
  execute(event: Event): Promise<Event> {
    event.library = "my-library-name/1.0.0";
    return Promise.resolve(event);
  }
}

カスタムプラグインをインストールするには、カスタムプラグインをパラメータとしてadd()を使用します。

typescript
import * as amplitude from "@amplitude/analytics-browser";
amplitude.add(new LibraryModifierPlugin());
amplitude.init(API_KEY, OPTIONAL_USER_ID);

初期化を遅らせる

amplitude-jsで初期化を延期するには、config.deferInitializationtrueに設定してinitを呼び出し、次にenableTracking()を呼び出して初期化を正式化し、キューに入れたすべてのイベントを送信します。

javascript
amplitude.getInstance().init(API_KEY, OPTIONAL_USER_ID, {
  deferInitialization: true,
});
amplitude.getInstance().logEvent("Event 1");
amplitude.getInstance().logEvent("Event 2");
amplitude.getInstance().logEvent("Event 3");
amplitude.getInstance().enableTracking();

ウェブアトリビューション

amplitude-jsでは、次の設定を使用してWebアトリビューションを有効にします。

  • config.includeGclid
  • config.includeFbclid
  • config.includeReferrer
  • config.includeUtm

@amplitude/analytics-browser@2+では、Webアトリビューションを1つの設定config.autocapture.attributionで制御できます。デフォルト設定はtrueで、すべてのキャンペーンのパラメータをキャプチャします。これらは、amplitude-jsがサポートしているのと同じキャンペーンパラメータです。

フラッシュまたは onExitPage

ユーザーがページから移動したときなど、イベントをすぐに送信する必要が生じる場合があります。即時送信は、イベントペイロードをバッチで送信しながらユーザーを別のページに誘導するボタンのクリックを追跡する場合に一般的です。

amplitude-jsで、onExitPage()コールバックを使用します。

javascript
amplitude.getInstance().init(API_KEY, OPTIONAL_USER_ID, {
  onExitPage: () => {
    amplitude.sendEvents();
  },
});

コールバック

amplitude-jsでは、初期化後に実行するinitコールバック関数1つと、ネットワークリクエストの成功およびエラーに対応する2つの独立したコールバック関数を受け付けます。@amplitude/analytics-browser@2+はPromiseとasync/awaitをサポートしているため、init()track()identify()groupIdentify()などの非同期メソッドはカスタムPromiseインターフェースを返します。

javascript
const initResult = await amplitude.init("YOUR_API_KEY").promise;
if (initResult.code === 200) {
  // success logic
} else {
  // error logic
}
const result = await amplitude.track("Button Clicked").promise;
if (result.code === 200) {
  // success logic
} else {
  // error logic
}

Was this helpful?