概要
このドキュメントでは、AndroidとiOSのReact Native連携の両方で共通して使用されるJavaScriptラッパー(PageSenseSDKWrapper.js)について説明します。このラッパーは、React Native Native Bridgeを介してPageSense SDKを操作するための統一されたJavaScriptインターフェースを提供し、プラットフォーム固有のネイティブモジュールの違いを抽象化します。
JavaScriptラッパーの作成
プロジェクトのルートから次のパスにラッパーファイルを作成します。
- src/sdk/PageSenseSDKWrapper.js
- javascript
- import { NativeModules } from 'react-native';
- const { PageSenseSDKModule }= NativeModules;
- export const GoalProperty= Object.freeze({
- REVENUE: 'revenue',
- });
- const VALID_GOAL_PROPERTIES= new Set(Object.values(GoalProperty));
- class PageSenseSDKWrapper {
- constructor() {}
- async initialiseSDK(accountId,sdkKey,projectName) {
- try {
- this._validateString(accountId, 'accountId');
- this._validateString(sdkKey, 'sdkKey');
- this._validateString(projectName, 'projectName');
- constresult = await PageSenseSDKModule.initialiseSDK(accountId,sdkKey,projectName);
- returnresult === true;
- } catch (error) {
- console.log('[PageSenseSDK] initialiseSDK error:',error);
- return false;
- }
- }
- async activateExperimentByContext(experimentName,userContext) {
- try {
- this._validateString(experimentName, 'experimentName');
- this._validateUserContext(userContext);
- constsafeUserContext = {
- userId: userContext.userId,
- userAttributes: userContext.userAttributes || {},
- };
- constvariation = await PageSenseSDKModule.activateExperimentByContext(
- experimentName,
- safeUserContext,
- );
- returnvariation ?? null;
- } catch (error) {
- console.log('[PageSenseSDK] activateExperimentByContext error:',error);
- return null;
- }
- }
- async getVariationNameByContext(experimentName,userContext) {
- try {
- this._validateString(experimentName, 'experimentName');
- this._validateUserContext(userContext);
- constsafeUserContext = {
- userId: userContext.userId,
- userAttributes: userContext.userAttributes || {},
- };
- constvariation = await PageSenseSDKModule.getVariationNameByContext(
- experimentName,
- safeUserContext,
- );
- returnvariation ?? null;
- } catch (error) {
- console.log('[PageSenseSDK] getVariationNameByContext error:',error);
- return null;
- }
- }
- trackGoalByContext(goalName,userContext,goalProperties) {
- try {
- this._validateString(goalName, 'goalName');
- this._validateUserContext(userContext);
- constsafeUserContext = {
- userId: userContext.userId,
- userAttributes: userContext.userAttributes || {},
- };
- if (goalProperties === undefined) {
- PageSenseSDKModule.trackGoalByContext(goalName,safeUserContext);
- } else {
- this._validateGoalPropertiesNonEmpty(goalProperties);
- PageSenseSDKModule.trackGoalWithPropertiesByContext(
- goalName,
- safeUserContext,
- goalProperties,
- );
- }
- } catch (error) {
- console.log('[PageSenseSDK] trackGoalByContext error:',error);
- }
- }
- _validateString(param,paramName) {
- if (typeofparam !== 'string'|| param.trim()=== '') {
- throw new Error(`[PageSenseSDK] Invalid ${paramName}: must be a non-empty string`);
- }
- }
- _validateAttributes(attributes) {
- if (attributes === undefined|| attributes === null) return;
- if (typeofattributes !== 'object'|| Array.isArray(attributes)) {
- throw new Error('[PageSenseSDK] attributesはキーと値のペアのオブジェクトである必要があります');
- }
- for (constkey inattributes) {
- if (typeofkey !== 'string'|| key.trim()=== '') {
- throw new Error('[PageSenseSDK] 属性キーが無効です。空でない文字列である必要があります');
- }
- constvalue = attributes[key];
- if (typeofvalue !== 'string') {
- throw new Error(`[PageSenseSDK] 属性「${key}」の値が無効です。使用できる型は文字列です`);
- }
- }
- }
- _validateUserContext(userContext) {
- if (
- userContext === undefined||
- userContext === null||
- typeofuserContext !== 'object'||
- Array.isArray(userContext)
- ) {
- throw new Error('[PageSenseSDK] userContextは有効なオブジェクトである必要があります');
- }
- this._validateString(userContext.userId, 'userContext.userId');
- if (userContext.userAttributes !== undefined&& userContext.userAttributes !== null) {
- this._validateAttributes(userContext.userAttributes);
- }
- }
- _validateGoalPropertiesNonEmpty(goalProperties) {
- if (goalProperties === null) {
- throw new Error(
- '[PageSenseSDK] goalPropertiesをnullにすることはできません。プロパティのない目標では、この引数を省略してください。',
- );
- }
- if (typeofgoalProperties !== 'object'|| Array.isArray(goalProperties)) {
- throw new Error('[PageSenseSDK] goalPropertiesはキーと値のオブジェクトである必要があります');
- }
- constkeys = Object.keys(goalProperties);
- if (keys.length === 0) {
- throw new Error(
- '[PageSenseSDK] goalPropertiesを空にすることはできません。プロパティのない目標では、この引数を省略してください。',
- );
- }
- for (constkey ofkeys) {
- if (!VALID_GOAL_PROPERTIES.has(key)) {
- throw new Error(
- `[PageSenseSDK] 無効な目標プロパティキー'${key}'。`+
- `次のいずれかである必要があります:${Array.from(VALID_GOAL_PROPERTIES).join(', ')}`,
- );
- }
- constvalue = goalProperties[key];
- if (typeofvalue !== 'string') {
- throw new Error(
- `[PageSenseSDK] 目標プロパティ'${key}'の値が無効です。使用可能な型:string`,
- );
- }
- }
- }
- }
- export default new PageSenseSDKWrapper();
SDK関数
initialiseSDK
PageSense SDKを初期化し、PageSenseClientインスタンスを作成します。他のSDK関数を使用する前に、アプリケーションの起動時に一度呼び出す必要があります。
メソッドシグネチャ
javascript
async initialiseSDK(accountId,sdkKey,projectName)
パラメーター
|
パラメーター
|
型
|
必須
|
説明
|
|
accountId
|
string
|
はい
|
PageSenseアカウントの識別子。
|
|
sdkKey
|
string
|
はい
|
認証に使用するSDKキー。
|
|
projectName
|
string
|
はい
|
PageSenseプロジェクトの名前。
|
戻り値の型
Promise<boolean> — SDKの初期化に成功した場合はtrue、失敗した場合はfalseを返します。
例
- javascript
- useEffect(()=> {
- async function initializeSDK() {
- try {
- constresult = await PageSenseSDKWrapper.initialiseSDK(
- 'PAGESENSE_ACCOUNT_ID',
- 'PAGESENSE_SDK_KEY',
- 'PAGESENSE_PROJECT_NAME',
- );
- setSdkReady(true);
- } catch (error) {
- setSdkReady(true);
- }
- }
- initializeSDK();
- }, []);
メモ
activateExperimentByContext
PageSenseUserContextを使用してユーザーに対してFullStackエクスペリメントを有効にし、ユーザーに割り当てられたバリエーションを返します。PageSenseにインプレッションイベントを送信し、訪問者の割り当てを保存します。
メソッドシグネチャ
javascript
async activateExperimentByContext(experimentName,userContext)
パラメーター
|
パラメーター
|
型
|
必須
|
説明
|
|
experimentName
|
string
|
はい
|
PageSenseで設定された実験の名前。
|
|
userContext
|
object
|
はい
|
ユーザーコンテキストオブジェクト(userIdと任意のuserAttributesを含む)。
|
|
userContext.userId
|
string
|
はい
|
ユーザーの一意の識別子。
|
|
userContext.userAttributes
|
object
|
いいえ
|
オーディエンスのターゲティングに使用されるユーザー属性のキーと値のペア。すべてのキーと値は文字列である必要があります。
|
戻り値の型
Promise<string|null>—ユーザーに割り当てられたバリエーション名を返します。バリエーションが割り当てられていない場合やエラーが発生した場合は、nullを返します。
例
- javascript
- constuserContext = {
- userId: 'USER_ID',
- userAttributes: {
- DeviceType: 'Phone',
- OS: 'Android',
- OSVersion: '14',
- DeviceModel: 'Pixel 8 Pro',
- },
- };
- constvariation = await PageSenseSDKWrapper.activateExperimentByContext(
- 'EXPERIMENT_NAME',
- userContext,
- );
- switch (variation) {
- case 'Original': setButtonColor('#4F46E5'); break;
- case 'Variation 1': setButtonColor('#EF4444'); break;
- case 'Variation 2': setButtonColor('#16A34A'); break;
- default: setButtonColor('#6B7280');
- }
メモ
getVariationNameByContext
実験を有効化せずに、PageSenseUserContextを使用してユーザーに割り当てられたバリエーションを取得します。インプレッションイベントは送信されず、訪問者の割り当ても保存されません。
訪問を記録せずにバリエーションを確認する必要がある場合に、この関数を使用します。たとえば、メインの実験フロー外でのログ記録や条件付きロジックで使用できます。
メソッドシグネチャ
javascript
async getVariationNameByContext(experimentName,userContext)
パラメーター
|
パラメーター
|
型
|
必須
|
説明
|
|
experimentName
|
string
|
はい
|
PageSenseで設定された実験の名前です。
|
|
userContext
|
object
|
はい
|
ユーザーコンテキストオブジェクト。含まれる項目:userId、任意のuserAttributes。
|
|
userContext.userId
|
string
|
はい
|
ユーザーの一意の識別子です。
|
|
userContext.userAttributes
|
object
|
いいえ
|
ユーザー属性のキーと値のペアです。すべてのキーと値は文字列である必要があります。
|
戻り値の型
Promise<string|null> — ユーザーに割り当てられたバリエーション名を返します。バリエーションが見つからない場合、またはエラーが発生した場合は null を返します。
例
- javascript
- constvariation = await PageSenseSDKWrapper.getVariationNameByContext(
- 'EXPERIMENT_NAME',
- userContext,
- );
- console.log('Variation Name:',variation);
注意事項
trackGoalByContext
PageSenseUserContextを使用して目標イベントをトラッキングします。目標に関連プロパティがあるかどうかに応じて、2通りの呼び出し方法に対応しています。
目標プロパティなし— FullStackカスタムイベント目標に使用します。
javascript
trackGoalByContext(goalName,userContext)
目標プロパティあり— 収益目標に使用します。
javascript
trackGoalByContext(goalName,userContext,goalProperties)
パラメーター
|
パラメーター
|
型
|
必須
|
説明
|
|
goalName
|
文字列
|
はい
|
PageSenseで設定された目標の名前。
|
|
userContext
|
オブジェクト
|
はい
|
ユーザーコンテキストオブジェクト(userIdと任意のuserAttributesを含む)。
|
|
userContext.userId
|
文字列
|
はい
|
ユーザーの一意の識別子。
|
|
userContext.userAttributes
|
オブジェクト
|
いいえ
|
ユーザー属性のキーと値のペア。すべてのキーと値は文字列である必要があります。
|
|
goalProperties
|
オブジェクト
|
いいえ
|
目標プロパティオブジェクト。キーはGoalProperty定数のいずれかである必要があります。指定する場合は空にできません。
|
戻り値の型
void
例 — プロパティなしでの目標の追跡
- javascript
- function handleSubmitButton() {
- constuserContext = {
- userId: 'USER_ID',
- userAttributes: { DeviceType: 'Phone', OS: 'Android' },
- };
- PageSenseSDKWrapper.trackGoalByContext('GOAL_NAME',userContext);
- }
例 — 収益目標の追跡
- javascript
- import PageSenseSDKWrapper, { GoalProperty } from './src/sdk/PageSenseSDKWrapper';
- function handleCompletePurchase(purchaseAmountInDollars) {
- constuserContext = {
- userId: 'USER_ID',
- userAttributes: { DeviceType: 'Phone', OS: 'Android' },
- };
- // ドルをセントに変換します:$100.50 → '10050'
- constrevenueInCents = String(Math.round(purchaseAmountInDollars * 100));
- constgoalProperties = {
- [GoalProperty.REVENUE]: revenueInCents,
- };
- PageSenseSDKWrapper.trackGoalByContext('PURCHASE_GOAL_NAME',userContext,goalProperties);
- }
- handleCompletePurchase(100.50);
注意事項
-
goalPropertiesを指定する場合は、空ではないオブジェクトにする必要があります。プロパティのない目標では、引数自体を省略してください。nullや空のオブジェクトは渡さないでください。
-
収益額は、セント単位の文字列として渡す必要があります。ドル額に100を掛け、最も近い整数に丸めてください。
-
特定のユーザー操作またはイベントが正常に完了した直後に、目標のトラッキングを実行してください。
GoalProperty定数
GoalProperty定数はPageSenseSDKWrapper.jsからエクスポートされており、ハードコードされた文字列の代わりに、goalPropertiesオブジェクトのキーとして使用する必要があります。
javascript
import { GoalProperty } from './src/sdk/PageSenseSDKWrapper';
|
JS定数
|
文字列値
|
Androidネイティブ定数
|
iOSネイティブ列挙型ケース
|
目的
|
|
GoalProperty.REVENUE
|
'revenue'
|
GoalProperty.REVENUE
|
GoalProperty.revenue
|
収益目標に使用する、セント単位の収益額
|
GoalPropertyキーがブリッジを介して渡される仕組み
-
Android—ネイティブKotlinモジュールは、GoalProperty.<CONSTANT>.valueとの照合により、各文字列キーを対応するGoalProperty列挙型定数にマッピングし、SDKに渡されるHashMap<GoalProperty, String>を生成します。
-
iOS—ネイティブSwiftモジュールは、GoalProperty(rawValue:)を使用して各文字列キーを対応するGoalProperty列挙型ケースにマッピングし、SDKに渡される[GoalProperty: String]ディクショナリーを生成します。
JavaScript: { [GoalProperty.REVENUE]: '10050' }
↓
文字列キー 'revenue' がブリッジを介して渡されます
↓
Android: HashMap { GoalProperty.REVENUE → '10050' }
iOS: [GoalProperty.revenue: '10050']
PageSenseUserContext の構造
- javascript
- constuserContext = {
- userId: 'USER_ID', // 必須—空でない文字列
- userAttributes: { // 任意—すべてのキーと値は文字列である必要があります
- DeviceType: 'Phone',
- OS: 'Android',
- OSVersion: '14',
- DeviceModel: 'Pixel 8 Pro',
- },
- };
|
項目
|
種類
|
必須
|
説明
|
|
userId
|
string
|
はい
|
ユーザーの一意の識別子です。空でない文字列である必要があります。
|
|
userAttributes
|
object
|
いいえ
|
オーディエンスのターゲティングに使用されるキーと値のペアです。すべてのキーと値は文字列である必要があります。省略した場合、初期設定では空のオブジェクトになります。
|