關於更多其他的 Custom templates API 方法可以參考 GTM 官方這篇:Custom template APIs
此次完整程式碼如下:
// Require the necessary APIs
const addEventCallback = require(\'addEventCallback\');
const readFromDataLayer = require(\'copyFromDataLayer\');
const sendPixel = require(\'sendPixel\');
const getTimestamp = require(\'getTimestamp\');
// Get the dataLayer event that triggered the tag
const event = readFromDataLayer(\'event\');
// Add a timestamp to separate events named the same way from each other
const eventTimestamp = getTimestamp();
const endPoint = data.endPoint;
const batchHits = data.batchHits === \'yes\';
const maxTags = data.maxTags;
// Utility for splitting an array into multiple arrays of given size
const splitToBatches = (arr, size) => {
const newArr = [];
for (let i = 0, len = arr.length; i < len; i += size) {
newArr.push(arr.slice(i, i + size));
}
return newArr;
};
// The addEventCallback gets two arguments: container ID and a data object with an array of tags that fired
addEventCallback((ctid, eventData) => {
// Filter out tags that have the "exclude" metadata set to true
const tags = eventData.tags.filter(t => t.exclude !== \'true\');
// If batching is enabled, split the tags into batches of the given size
const batches = batchHits ? splitToBatches(tags, maxTags) : [tags];
// For each batch, build a payload and dispatch to the endpoint as a GET request
batches.forEach(tags => {
let payload = \'?eventName=\' + event + \'&eventTimestamp=\' + eventTimestamp;
tags.forEach((tag, idx) => {
const tagPrefix = \'&tag\' + (idx + 1);
payload +=
tagPrefix + \'id=\' + tag.id +
tagPrefix + \'nm=\' + tag.name +
tagPrefix + \'st=\' + tag.status +
tagPrefix + \'et=\' + tag.executionTime;
log([\'GTM_Tag Status\'],tag.status);
});
log([\'GTM_This is payload\'],payload);
sendPixel(endPoint + payload, null, null);
});
});
// After adding the callback, signal tag completion
data.gtmOnSuccess();
// 代碼結束時呼叫 data.gtmOnSuccess。
data.gtmOnSuccess();
可以看到 const endPoint = data.endPoint; 這邊的 endPoint 就是使用者輸入的文字框內的值,這邊將參數附加在 endPoint 後面,最後再用Custom template 提供的 sendPixel API 來向指定的 URL 發送 GET 請求,最後代碼結束時需呼叫 data.gtmOnSuccess()