イベントおよび訪問関数の例 (V3)
この記事では、V3イベントおよび訪問関数のサンプルコードを提供します。
HTTP GETを使用してイベントデータを送信
次の例は、イベントデータをクエリ文字列パラメータとしてエンドポイントにHTTP GETリクエストを行う方法を示しています。
activate(({ event }) => {
console.log(JSON.stringify(event));
fetch(encodeURI(`https://webhook.site/87bb160f-475a-4258-b117-693bb2378a4d?param=${event.data}`))
.then(response => {
if (!response.ok) {
throw new Error(`Network response was not ok. Status code: ${response.status}.`);
}
return response.json();
})
.then(data => console.log('Response:', JSON.stringify(data)))
.catch(error => console.log('Error:', error.message));
})
HTTP POSTを使用して訪問データを送信
次の例は、訪問プロファイルデータをリクエストボディJSONに含めてエンドポイントにHTTP POSTリクエストを行う方法を示しています。
activate(({ visitor }) => {
console.log(JSON.stringify(visitor));
fetch('https://webhook.site/87bb160f-475a-4258-b117-693bb2378a4d',
{
method: 'POST',
body: JSON.stringify(visitor),
headers: {
'Content-Type': 'application/json'
}
})
.then(response => {
if (!response.ok) {
throw new Error(`Network response was not ok. Status code: ${response.status}.`);
}
return response.json();
})
.then(data => console.log('Response:', JSON.stringify(data)))
.catch(error => console.log('Error:', error.message));
})
HTTP GETを使用して訪問データを送信
次の例は、訪問プロファイルデータをクエリ文字列パラメータとしてエンドポイントにHTTP GETリクエストを行う方法を示しています。
activate(({ visit }) => {
console.log(JSON.stringify(visit)); // notice separate visit property
fetch(encodeURI(`https://webhook.site/87bb160f-475a-4258-b117-693bb2378a4d?param=${visit.creation_ts}`))
.then(response => {
if (!response.ok) {
throw new Error(`Network response was not ok. Status code: ${response.status}.`);
}
return response.json();
})
.then(data => console.log('Response:', JSON.stringify(data)))
.catch(error => console.log('Error:', error.message));
})
Tealium Collect HTTP APIにイベントを送信
次の例は、データを取得し、Tealium Collectにイベントを送信する方法を示しています。
activate(async ({ event }) => {
const searchQuery = new URLSearchParams({ path: event.data.dom.pathname, query: event.data.dom.search_query });
const newEvent = await fetch(`https://getnew.event.com?${searchQuery}`)
.then(response => {
if (!response.ok) {
throw new Error(`Network response was not ok. Status code: ${response.status}.`);
}
return response.json();
});
track(newEvent, {
tealium_account: event.account,
tealium_profile: event.profile,
tealium_datasource: 'p9v81m'
})
.then(response => {
if(!response.ok){
throw new Error(`Network response was not ok. Status code: ${response.status}.`);
}
return response.text();
})
.then(data => console.log('Result : ', data))
.catch(error => console.error('Error:', error.message));
})
サービスプロバイダーへの呼び出しに認証アクセストークンを使用
この例では、OAuth 2.0認証を使用してGoogle Firebase Cloud MessagingへのAPI呼び出しを行います。関数にOAuth2.0認証を追加すると作成されるアクセストークンは、helper.getAuth()
へのパラメータとして渡されます。次の図は、この例の関数のアクセストークンを示しています:
次のコード例は、firebase cloud messagingでメッセージを送信するAPI呼び出しを行う際にhelper.getAuth()
を呼び出して認証を取得する方法を示しています:
activate(async ({ visitor, helper }) => {
const response = await fetch(
"https://fcm.googleapis.com/v1/projects/YOURPROJECT/messages:send",
{
method: "POST",
headers: {
'Authorization': 'Bearer '+helper.getAuth('firebase_cloud_messaging'),
'Content-Type': 'application/json'
},
body:body
}
);
});
const response = await fetch(
"https://fcm.googleapis.com/v1/projects/YOURPROJECT/messages:send",
{
method: "POST",
headers: {
`Authorization': 'Bearer '+auth.get('firebase_cloud_messaging'),
'Content-Type': 'application/json'
},
body:body
}
);
グローバル変数の値を取得
次のコード例は、helper.getGlobalVariable()
を使用してグローバル変数Cloud_function_URL
を取得し、このURLを使用してGoogle cloud functionを呼び出す方法を示しています。
const cfunction_url = helper.getGlobalVariable("Cloud_function_URL");
let headers = {
"content-type": "application/json",
"mute-http-exceptions": "true"
};
// code to populate body parameter goes here
const response = await fetch(cfunction_url, {
method: "POST",
headers: headers,
body: body
});
イベントまたは訪問関数用のグローバル変数を作成する方法については、イベントまたは訪問関数用のグローバル変数を追加するを参照してください。
属性IDによる属性名または属性値の取得
属性名は変更されることがあり、コードが属性名を参照している場合に問題が発生する可能性があります。属性名が変更されても、属性IDは変更されません。属性名の変更による問題を避けるために、event
、visitor
、およびvisit
オブジェクトが提供するgetAttrNameById()
およびgetAttrValueByID()
メソッドを使用して属性をIDで参照することができます。
getAttrValueByID()
メソッドは控えめに使用することをお勧めします。この方法では、イベントまたは訪問オブジェクトのプロパティを再帰的に検索して値を見つけます。イベントまたは訪問オブジェクトが複雑な場合、この操作により関数呼び出しの計算時間が増加する可能性があります。
関数にgetAttrNameById()
またはgetAttrValueByID()
を追加すると、コード補完機能が使用する属性IDを選択するのに役立ちます。たとえば、コードエディタに次のように入力すると、開き括弧を入力すると、コード補完機能が属性と関連するIDのリストを表示します:
属性名の一部を入力してリストをフィルタリングすることができます。属性を選択すると、そのIDが括弧の後にコードに追加されます。
最終更新日 :: 2025年October月2日