概要
このドキュメントでは、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);
- 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);
- 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);
- 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);
- }
- }
- _validateString(param,paramName) {
- if (typeofparam !== 'string'|| param.trim()=== '') {
- throw new Error(`[PageSenseSDK] 無効な${paramName}:空でない文字列を指定してください`);
- }
- }
- _validateAttributes(attributes) {
- if (attributes === undefined|| attributes === null) return;
- if (typeofattributes !== 'object'|| Array.isArray(attributes)) {
- throw new Error('[PageSenseSDK] 属性はキーと値の形式のオブジェクトである必要があります');
- }
- 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関数を使用する前に1回呼び出す必要があります。
メソッドシグネチャ
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を使用してユーザーに対してフルスタックテストを有効化し、そのユーザーに割り当てられたバリエーションを返します。インプレッションイベントをPageSenseに送信し、訪問者への割り当てを保持します。
メソッドシグネチャー
javascript
async activateExperimentByContext(experimentName,userContext)
パラメーター
|
パラメーター
|
型
|
必須
|
説明
|
|
experimentName
|
文字列
|
はい
|
PageSenseで設定されているテスト名です。
|
|
userContext
|
オブジェクト
|
はい
|
必須の userId と任意の userAttributes を含むユーザーコンテキストオブジェクトです。
|
|
userContext.userId
|
文字列
|
はい
|
ユーザーの一意の識別子です。
|
|
userContext.userAttributes
|
オブジェクト
|
いいえ
|
オーディエンスのターゲティングに使用するユーザー属性のキーと値のペアです。すべてのキーと値は文字列である必要があります。
|
戻り値の型
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);
注意事項
trackGoalByContext
PageSenseUserContextを使用して目標イベントを追跡します。目標に関連付けられたプロパティがあるかどうかに応じて、2通りの呼び出し方法を使用できます。
目標プロパティなし—フルスタックのカスタムイベント目標に使用します。
javascript
trackGoalByContext(goalName,userContext)
目標プロパティあり—売上目標に使用します。
javascript
trackGoalByContext(goalName,userContext,goalProperties)
パラメーター
|
パラメーター
|
型
|
必須
|
説明
|
|
goalName
|
string
|
はい
|
PageSenseで設定した目標の名前。
|
|
userContext
|
object
|
はい
|
ユーザーコンテキストオブジェクト(userIdおよび任意のuserAttributesを含む)。
|
|
userContext.userId
|
string
|
はい
|
ユーザーの一意の識別子。
|
|
userContext.userAttributes
|
object
|
いいえ
|
ユーザー属性のキーと値のペア。すべてのキーと値は文字列にする必要があります。
|
|
goalProperties
|
object
|
いいえ
|
目標プロパティオブジェクト。キーには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列挙型定数にマッピングします。これにより生成されたHashMap<GoalProperty, String>がSDKに渡されます。
-
iOS—ネイティブのSwiftモジュールは、GoalProperty(rawValue:)を使用して、各文字列キーを対応するGoalProperty列挙型ケースにマッピングします。これにより生成された[GoalProperty: String]辞書がSDKに渡されます。
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
|
文字列
|
はい
|
ユーザーの一意の識別子です。空でない文字列を指定する必要があります。
|
|
userAttributes
|
オブジェクト
|
いいえ
|
オーディエンスのターゲティングに使用するキーと値のペアです。すべてのキーと値は文字列である必要があります。省略した場合、初期設定では空のオブジェクトになります。
|