伺服器端標記 API

本文說明伺服器端代碼的 API。


addEventCallback

註冊回呼函式,在事件結束時叫用。事件的所有代碼都執行完畢後,系統就會叫用回呼。回呼會傳遞兩個值:叫用函式的容器 ID,以及包含事件相關資訊的物件。

在代碼中使用這個 API 時,API 會與目前事件建立關聯。在用戶端使用這個 API 時,必須透過 runContainer API 的 bindToEvent 函式,將其繫結至特定事件。詳情請參閱範例。

語法

const addEventCallback = require('addEventCallback');

addEventCallback((containerId, eventData) => {
  // Take some action based on the event data.
});

參數

參數 類型 說明
callback 函式 事件結束時要叫用的函式。

eventData 物件包含下列資料:

鍵名 類型 說明
tags 陣列 標記資料物件陣列。事件期間觸發的每個代碼都會在這個陣列中顯示一個項目。代碼資料物件包含代碼 ID (id)、執行狀態 (status) 和執行時間 (executionTime)。代碼資料也會包含代碼上設定的其他代碼中繼資料。

範例

在用戶端中:

const addEventCallback = require('addEventCallback');
const claimRequest = require('claimRequest');
const extractEventsFromMpv1 = require('extractEventsFromMpv1');
const logToConsole = require('logToConsole');
const returnResponse = require('returnResponse');
const runContainer = require('runContainer');

claimRequest();

const events = extractEventsFromMpv1();
let eventsCompleted = 0;
events.forEach((evt, i) => {
  runContainer(evt, /* onComplete= */ (bindToEvent) => {
    bindToEvent(addEventCallback)((containerId, eventData) => {
      logToConsole('Event Number: ' + i);
      eventData.tags.forEach((tag) => {
        logToConsole('Tag ID: ' + tag.id);
        logToConsole('Tag Status: ' + tag.status);
        logToConsole('Tag Execution Time: ' + tag.executionTime);
      });
    });
    if (events.length === ++eventsCompleted) {
      returnResponse();
    }
  });
});

在代碼中:

const addEventCallback = require('addEventCallback');

addEventCallback((containerId, eventData) => {
  // This will be called at the end of the current event.
});

相關權限

read_event_metadata


callLater

排定以非同步方式呼叫函式。目前的程式碼傳回後,系統會呼叫該函式。這相當於 setTimeout(<function>, 0)。

範例

const callLater = require('callLater');
const logToConsole = require('logToConsole');

callLater(() => {
  logToConsole('Logged asynchronously');
});

語法

callLater(function)

參數

參數 類型 說明
function 函式 要呼叫的函式。

相關權限

無。


claimRequest

在用戶端使用這個 API 聲明要求。要求一經認領,容器就不會執行其他用戶端。

如果在代碼或變數中呼叫這個 API,系統會擲回例外狀況。如果在用戶端傳回後呼叫 (例如在 callLater 或 runContainer onComplete 函式等非同步回呼中呼叫),這個 API 會擲回例外狀況。

用戶端應先使用這個 API 聲明要求,再呼叫 runContainer API。

範例

const claimRequest = require('claimRequest');

claimRequest();

語法

claimRequest();

相關權限

無。


computeEffectiveTldPlusOne

傳回指定網域或網址的有效頂層網域 + 1 (eTLD+1)。 系統會根據公開尾碼清單規則評估網域,計算出 eTLD+1。eTLD+1 通常是可設定 Cookie 的最高層級網域。

如果引數為空值或未定義,則會傳回未經修改的引數值。否則引數會強制轉型為字串。如果引數不是有效的網域或網址,則會傳回空白字串。如果伺服器無法擷取公用後置字串清單,則會傳回未變更的引數值。

範例

const computeEffectiveTldPlusOne = require('computeEffectiveTldPlusOne');

// Returns 'example.co.uk'
computeEffectiveTldPlusOne('analytics.example.co.uk');

// Returns 'example.co.uk'
computeEffectiveTldPlusOne('https://analytics.example.co.uk/path');

語法

computeEffectiveTldPlusOne(domainOrUrl);

參數

參數 類型 說明
domainOrUrl string 要計算 eTLD+1 的網域或網址。

相關權限

無。


createRegex

建立新的 regex 例項,並傳回包裝在物件中的例項。您無法直接存取規則運算式。不過,您可以將其傳遞至 testRegex API、String.replace()、String.match() 和 String.search()。

如果規則運算式無效,或伺服器上沒有 Re2,則會傳回 null。

這個 API 使用 Re2 實作。伺服器 Docker 映像檔必須是 2.0.0 以上版本。

範例

const createRegex = require('createRegex');

const domainRegex = createRegex('\\w+\\.com', 'i');

// Returns '/foobar'
'example.com/foobar'.replace(domainRegex, '');

語法

createRegex(pattern, flags);

參數

參數 類型 說明
pattern string 規則運算式的文字。
flags string 選用字串,包含所建立規則運算式的旗標。 支援「g」(全域) 和「i」(忽略大小寫)。系統會忽略所有其他字元。

相關權限

無。

最低映像檔版本

2.0.0


decodeUri

將所提供 URI 中的任何編碼字元解碼。傳回代表已解碼 URI 的字串。如果輸入內容無效,則會傳回 undefined。

範例

const decodeUri = require('decodeUri');

const decodedUrl = decodeUri(data.encodedUrl);
if (decodedUrl) {
  // ...
}

語法

decodeUri(encoded_uri);

參數

參數 類型 說明
encoded_uri string 由 encodeUri() 或其他方式編碼的 URI。

相關權限

無。


decodeUriComponent

將所提供 URI 元件中的任何編碼字元解碼。傳回代表已解碼 URI 元件的字串。如果輸入內容無效,則會傳回 undefined。

範例

const decodeUriComponent = require('decodeUriComponent');

const decodedQuery = decodeUriComponent(data.query);
if (decodedQuery) {
  // ...
}

語法

decodeUriComponent(encoded_uri_component);

參數

參數 類型 說明
encoded_uri_component string 由 encodeUriComponent() 或其他方式編碼的 URI 元件。

相關權限

無。


encodeUri

透過逸出特殊字元,傳回編碼的統一資源識別項 (URI)。傳回字串,代表以 URI 編碼的指定字串。

範例

const encodeUri = require('encodeUri');
const sendHttpGet = require('sendHttpGet');

sendHttpGet('https://www.example.com/' + encodeUri(pathInput));

語法

encodeUri(uri);

參數

參數 類型 說明
uri string 完整的 URI。

相關權限

無。


encodeUriComponent

透過逸出特殊字元,傳回編碼的統一資源識別項 (URI)。傳回字串,代表以 URI 形式編碼的指定字串。

範例

const encodeUriComponent = require('encodeUriComponent');
const sendHttpGet = require('sendHttpGet');

sendHttpGet('https://www.example.com/?' + encodeUriComponent(queryInput));

語法

encodeUriComponent(str);

參數

參數 類型 說明
str string URI 的元件。

相關權限

無。


extractEventsFromMpv1

將傳入的 Measurement Protocol V1 要求,轉譯為 Unified Schema 格式的事件清單。傳回擷取的事件清單。如果要求格式不正確,系統會擲回錯誤。

範例

const extractEventsFromMpv1 = require('extractEventsFromMpv1');
const isRequestMpv1 = require('isRequestMpv1');

if (isRequestMpv1()) {
  const events = extractEventsFromMpv1();
  for (let i = 0; i < events.length; ++i) {
    const event = events[i];
    // Process event.
  }
}

語法

extractEventsFromMpv1();

相關權限

需要 read_request 權限。權限必須設定為至少允許存取:

  • body
  • query parameters

extractEventsFromMpv2

將傳入的 Measurement Protocol V2 要求,轉譯為統一結構定義格式的事件清單。傳回擷取的事件清單。如果要求格式不正確,系統會擲回錯誤。

範例

const extractEventsFromMpv2 = require('extractEventsFromMpv2');
const isRequestMpv2 = require('isRequestMpv2');

if (isRequestMpv2()) {
  const events = extractEventsFromMpv2();
  for (let i = 0; i < events.length; ++i) {
    const event = events[i];
    // Process event.
  }
}

語法

extractEventsFromMpv2();

相關權限

需要 read_request 權限。權限必須設定為至少允許存取:

  • body
  • query parameters

fromBase64

將 Base64 編碼字串解碼。如果輸入內容無效,則會傳回 undefined。

語法

fromBase64(base64EncodedString);

參數

參數 類型 說明
base64EncodedString string Base64 編碼字串。

範例

const fromBase64 = require('fromBase64');

const greeting = fromBase64('aGVsbG8=');
if (greeting === 'hello') {
  // ...
}

相關權限

無。


generateRandom

傳回指定範圍內的隨機數字 (整數)。

範例

const generateRandom = require('generateRandom');

const randomValue = generateRandom(0, 10000000);

語法

generateRandom(min, max);

參數

參數 類型 說明
min number 傳回整數的可能最小值 (含)。
max number 傳回整數的最大可能值 (含)。

相關權限

無。


getAllEventData

傳回事件資料的副本。

語法

getAllEventData();

相關權限

read_event_data


getAnonymizedIpAddress

傳回要求來源 IP 位址的去識別化字串表示法。

如果是 IPv4 位址,最後一個八位元會遮蓋為 0 (例如 198.51.100.42 變成 198.51.100.0)。如果是 IPv6 位址,最後 80 個位元會遮蓋為零,保留前 48 個位元 (例如 2001:db8:cafe:1234:5678:90ab:cdef:1234 變成 2001:db8:cafe::)。

如果 IP 位址無效或無法解析,則傳回 "::",因此結果一律可以安全地用作 ip_override。

範例

const getAnonymizedIpAddress = require('getAnonymizedIpAddress');

const anonymizedIp = getAnonymizedIpAddress();

語法

getAnonymizedIpAddress();

相關權限

user_ip


getClientName

傳回包含目前用戶端名稱的字串。

語法

getClientName();

相關權限

read_container_data


getContainerVersion

傳回包含目前容器相關資料的物件。傳回的物件包含下列欄位:

{
  containerId: string,
  debugMode: boolean,
  environmentName: string,
  environmentMode: boolean,
  previewMode: boolean,
  version: string,
}

範例

const getContainerVersion = require('getContainerVersion');

const containerVersion = getContainerVersion();
const containerId = containerVersion['containerId'];
const isDebug = containerVersion['debugMode'];

語法

getContainerVersion();

相關權限

read_container_data


getCookieValues

傳回陣列,其中包含名稱與指定名稱相符的所有 Cookie 值。

範例

const getCookieValues = require('getCookieValues');

const lastVisit = getCookieValues('lastVisit')[0];
if (lastVisit) {
  // ...
}

語法

getCookieValues(name[, noDecode]);

參數

參數 類型 說明
name string Cookie 的名稱。
noDecode boolean 如果設為 true,Cookie 值就不會在傳回前解碼。預設為 false。

相關權限

get_cookies


getEventData

傳回事件資料中指定路徑的值副本。如果沒有事件資料,或指定路徑沒有值,則傳回 undefined。

範例

const getEventData = require('getEventData');

const campaignId = getEventData('campaign.id');
const itemId = getEventData('items.0.id');
const referrer = getEventData('page_referrer');

參數

參數 類型 說明
keyPath any 金鑰路徑,其中路徑元件以半形句號分隔。路徑元件可以是物件中的鍵或陣列中的索引。如果 keyPath 不是字串,則會強制轉型為字串。

語法

getEventData(keyPath);

相關權限

read_event_data


getGoogleAuth

傳回授權物件,與 sendHttpGet 或 sendHttpRequest 搭配使用時,會包含 Google Cloud API 的授權標頭。這個 API 會使用應用程式預設憑證,自動從伺服器環境尋找憑證。

範例

const getGoogleAuth = require('getGoogleAuth');
const logToConsole = require('logToConsole');
const sendHttpGet = require('sendHttpGet');

const auth = getGoogleAuth({
  scopes: ['https://www.googleapis.com/auth/datastore']
});

sendHttpGet(
  'https://firestore.googleapis.com/v1/projects/my-project/databases/(default)/documents/collection/document',
  {authorization: auth}
).then((result) => {
  if (result.statusCode >= 200 && result.statusCode < 300) {
    logToConsole('Result: ' + result.body);
    data.gtmOnSuccess();
  } else {
    data.gtmOnFailure();
  }
});

語法

getGoogleAuth(scopes);

參數

參數 類型 說明
scopes 陣列 OAuth 2.0 Google API 範圍陣列,用於要求存取權。

相關權限

需要 use_google_credentials 權限。權限必須設定一或多個允許的範圍。


getGoogleScript

從預先決定的 Google 指令碼組合中擷取資源,並傳回包含指令碼和相關快取中繼資料的 Promise。

Promise 會解析為包含兩個鍵的物件:script 和 metadata。如果要求失敗,Promise 會拒絕並傳回 reason 鍵。

metadata 物件會根據資源回應標頭,包含下列快取中繼資料;只有在資源回應中出現對應的標頭時,才會顯示各個欄位。

{
  'cache-control': string,
  'expires': string,
  'last-modified': string,
}

範例

const getGoogleScript = require('getGoogleScript');

getGoogleScript('ANALYTICS').then((result) => {
  // Operate on result.script and result.metadata here.
});

語法

getGoogleScript(script[, options]);

參數

參數 類型 說明
script string 指令碼名稱。支援的指令碼為 'ANALYTICS'、'GTAG' 和 'GTM'。

'ANALYTICS' 選項會從 https://www.google-analytics.com/analytics.js 擷取 Google Analytics 指令碼。

'GTAG' 選項會從 https://www.googletagmanager.com/gtag/js 擷取全域網站代碼 (gtag.js) 指令碼。

'GTM' 選項會從 https://www.googletagmanager.com/gtm.js 擷取 Google 代碼管理工具指令碼。
options 物體 選用要求選項。請參閱下方支援的選項。

選項

選項 類型 說明
id string 適用於含有 gtag 評估 ID 的 'GTAG',以及 含有網站容器 ID 的 'GTM' (例如 GTM-XXXX)。
debug any 如果為 truthy,則會要求並傳回評估指令碼的偵錯版本。
timeout number 要求逾時時間 (以毫秒為單位);系統會忽略非正值。如果要求逾時,系統會叫用回呼,並將指令碼值設為 undefined,中繼資料物件設為 {}。

系統會忽略無法辨識的選項鍵。

相關權限

需要 send_http 權限。權限設定必須至少允許存取:

  • 允許 Google 網域

getRemoteAddress

讀取 Forwarded 和 X-Forwarded-For 等要求標頭,傳回要求來源 IP 位址的字串表示法,例如 IPv4 的 12.345.67.890 或 IPv6 的 2001:0db8:85a3:0:0:8a2e:0370:7334。注意:這個 API 會盡可能找出原始 IP,但無法保證結果準確。

語法

getRemoteAddress();

相關權限

需要 read_request 權限。權限必須設定為至少允許存取:

  • 標頭 Forwarded 和 X-Forwarded-For
  • 遠端 IP 位址

getRequestBody

傳回要求主體 (如有),格式為字串,否則傳回 undefined。

語法

getRequestBody();

相關權限

read_request


getRequestHeader

以字串形式傳回指定要求標頭的值 (如有),否則傳回 undefined。如果標頭重複,傳回的值會與 ', ' 結合。

範例

const getRequestHeader = require('getRequestHeader');

const host = getRequestHeader('host');

語法

getRequestHeader(headerName);

參數

參數 類型 說明
headerName string 標頭名稱。這個值不區分大小寫。

相關權限

read_request


getRequestMethod

以字串形式傳回要求方法,例如 'GET' 或 'POST'。

範例

const getRequestMethod = require('getRequestMethod');

if (getRequestMethod() === 'POST') {
  // Handle the POST request here.
}

語法

getRequestMethod();

相關權限

無。


getRequestPath

傳回不含查詢字串的要求路徑。舉例來說,如果網址是 '/foo?id=123',則會傳回 '/foo'。自動從路徑中移除伺服器容器網址前置字元。舉例來說,如果伺服器容器網址為 https://example.com/analytics,要求路徑為 '/analytics/foo',則會傳回 '/foo'。

範例

const getRequestPath = require('getRequestPath');

const requestPath = getRequestPath();
if (requestPath === '/') {
  // Handle a request for the root path.
}

語法

getRequestPath();

相關權限

read_request


getRequestQueryParameter

以字串形式傳回已解碼的指定查詢字串參數值,如果參數不存在,則傳回 undefined。如果參數在查詢字串中重複,系統會傳回查詢字串中顯示的第一個值。

範例

const getRequestQueryParameter = require('getRequestQueryParameter');

const query = getRequestQueryParameter('query');
if (query) {
  // Process query here.
}

語法

getRequestQueryParameter(name);

參數

參數 類型 說明
name string 查詢參數名稱。

相關權限

read_request


getRequestQueryParameters

傳回傳入 HTTP 要求的查詢參數,做為將查詢參數名稱對應至對應值的物件。參數名稱和值會解碼。

範例

const getRequestQueryParameters = require('getRequestQueryParameters');

const queryParameters = getRequestQueryParameters();
if (queryParameters['search']) {
  // Handle the search query here.
  const maxResults = queryParameters['max_results'];
}

語法

getRequestQueryParameters();

相關權限

read_request


getRequestQueryString

以字串形式傳回要求查詢 (不含開頭的問號),如果要求網址不含查詢字串,則傳回空字串。

範例

const getRequestQueryString = require('getRequestQueryString');

const queryString = getRequestQueryString();
if (queryString !== '') {
  // Handle the query string.
}

語法

getRequestQueryString();

相關權限

read_request


getTimestamp

已淘汰。建議使用 getTimestampMillis。

傳回數字,代表自 Unix 紀元以來的目前時間 (以毫秒為單位),由 Date.now() 傳回。

語法

getTimestamp();

相關權限

無。


getTimestampMillis

傳回數字,代表自 Unix 紀元以來的目前時間 (以毫秒為單位),由 Date.now() 傳回。

語法

getTimestampMillis();

相關權限

無。


getType

傳回說明指定值類型的字串。

輸入類型 傳回值
string 'string'
number 'number'
boolean 'boolean'
空值 'null'
undefined 'undefined'
陣列 'array'
物件 'object'
功能 'function'

範例

const getType = require('getType');

const type = getType(value);
if (type === 'string') {
  // Handle string input.
} else if (type === 'number') {
  // Handle numeric input.
} else {
  logToConsole('Unsupported input type: ', type);
}

語法

getType(value);

參數

參數 類型 說明
value any 輸入值。

相關權限

無。


hmacSha256

使用雜湊式訊息驗證碼 (HMAC) 搭配 SHA-256 計算編碼簽章。預設為 base64url 編碼。

如要使用這個 API,請將伺服器上的 SGTM_CREDENTIALS 環境變數設為 UTF-8 編碼 JSON 金鑰檔案的路徑,格式如下:

{
  "keys": {
    "key1": "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXowMTIzNDU2Nzg5",
    "key2": "OTg3NjU0MzIxMHp5eHd2dXRzcnFwb25tbGtqaWhnZmVkY2Jh",
    ...
  }
}

值是採用 Base64 編碼的 HMAC 金鑰。JSON 文字開頭不得為位元組順序標記。

範例

const hmacSha256 = require('hmacSha256');
const toBase64 = require('toBase64');

const header = toBase64('{"alg":"HS256","typ":"JWT"}', {urlEncoding: true});
const claim = toBase64('{"sub":"1234567890","iat":1698164946}', {urlEncoding: true});
const signature = hmacSha256(header + '.' + claim, 'key1');

const jwt = header + "." + claim + '.' + signature;

語法

hmacSha256(data, keyId, options)

參數

參數 類型 說明
data string 用於計算 HMAC 值的資料。
keyId string JSON 金鑰檔案中的金鑰 ID,參照要使用的金鑰。
options object 選用 API 設定。(請參閱下方的「選項」)。

選項

選項 類型 說明
outputEncoding string 指定傳回值的編碼格式。支援的格式為 hex、base64 或 base64url。如未指定,則預設為 base64url。

相關權限

use_custom_private_keys

最低映像檔版本

1.0.0


isRequestMpv1

如果傳入的要求是 Measurement Protocol V1 要求,則傳回 true,否則傳回 false。

範例

const isRequestMpv1 = require('isRequestMpv1');

if (isRequestMpv1()) {
  // Handle Measurement Protocol V1 request.
  const events = extractEventsFromMpv1();
}

語法

isRequestMpv1();

相關權限

無。


isRequestMpv2

如果傳入的要求是 Measurement Protocol V2 要求,則傳回 true,否則傳回 false。

範例

const isRequestMpv2 = require('isRequestMpv2');

if (isRequestMpv2()) {
  // Handle Measurement Protocol V2 request.
  const events = extractEventsFromMpv2();
}

語法

isRequestMpv2();

相關權限

無。


logToConsole

將引數記錄到控制台。

您可以在 Google Cloud 控制台的Logs Explorer中查看這些記錄。在 Logs Explorer 中執行查詢 logName =~ "stdout",查看這個 API 建立的記錄項目。

範例

const logToConsole = require('logToConsole');

const that = 123;
const those = { ... };
logToConsole('that is: ', that, ' and those is: ', those);

語法

logToConsole(argument1[, argument2, ...]);

參數

API 會採用一或多個引數,每個引數都會轉換為字串 (如有必要),並記錄到控制台。

相關權限

logging


makeInteger

將指定值轉換為數字 (整數)。

語法

makeInteger(value);

參數

參數 類型 說明
value any type 要轉換的值。

相關權限

無。


makeNumber

將指定值轉換為數字。

語法

makeNumber(value);

參數

參數 類型 說明
value any type 要轉換的值。

相關權限

無。


makeString

以字串形式傳回指定值。

語法

makeString(value);

參數

參數 類型 說明
value any type 要轉換的值。

相關權限

無。


makeTableMap

將含有兩欄的簡單表格物件轉換為 Map。這可用於將包含兩欄的 SIMPLE_TABLE 範本欄位變更為更易於管理的格式。

舉例來說,這個函式可以轉換表格物件:

[
  {'key': 'k1', 'value': 'v1'},
  {'key': 'k2', 'value': 'v2'}
]

轉換為 Map:

{
  'k1': 'v1',
  'k2': 'v2'
}

傳回物件:已新增轉換後的鍵/值組合 Map,否則為 null。

語法

makeTableMap(tableObj, keyColumnName, valueColumnName);

參數

參數 類型 說明
tableObj 清單 要轉換的資料表物件。這是一份對應清單,其中每個 Map 代表資料表中的一個資料列。資料列物件中的每個屬性名稱都是資料欄名稱,而屬性值則是資料列中的資料欄值。
keyColumnName string 這個資料欄的值會成為轉換後 Map 的鍵。
valueColumnName string 資料欄名稱,其值會成為轉換後 Map 中的值。

相關權限

無。


parseUrl

傳回包含指定網址所有組成部分的物件,類似於 URL 物件。

如果網址格式錯誤,這個 API 會傳回 undefined。如果網址格式正確,網址字串中未出現的欄位會是空字串值,如果是 searchParams,則會是空物件。

傳回的物件會包含下列欄位:

{
  href: string,
  origin: string,
  protocol: string,
  username: string,
  password: string,
  host: string,
  hostname: string,
  port: string,
  pathname: string,
  search: string,
  searchParams: Object<string, (string|Array)>,
  hash: string,
}

範例

const parseUrl = require('parseUrl');

const urlObject = parseUrl('https://abc:xyz@example.com:8080/foo?param=val%2Cue#bar');

語法

parseUrl(url);

參數

參數 類型 說明
url string 要剖析的完整網址。

相關權限

無。


returnResponse

使用修改回應的 API (包括 setCookie、setPixelResponse、setResponseBody、setResponseHeader 和 setResponseStatus),清除先前由其他範本設定的回應。預設為 HTTP 狀態碼 200、空白主體和無標頭。

建議您從用戶端範本使用這個 API。

語法

returnResponse();

範例

請參閱 runContainer 範例。

相關權限

return_response


runContainer

在事件範圍內執行容器邏輯 (變數、觸發條件、代碼)。如果在容器執行期間呼叫這個 API,容器會再次執行。

onComplete 和 onStart 回呼會收到名為 bindToEvent 的函式。使用 bindToEvent 在事件情境中執行 API。詳情請參閱 addEventCallback 範例。

建議您從用戶端範本使用這個 API。

範例

const returnResponse = require('returnResponse');
const runContainer = require('runContainer');

// Runs the container with a simple pageview event and then returns a response.
runContainer({'event_name': 'pageview'}, () => returnResponse());

語法

runContainer(event, onComplete, onStart);

參數

參數 類型 說明
event 物體 事件參數。
onComplete 函式 所有代碼觸發完畢後叫用的回呼。
onStart 函式 在代碼開始觸發前立即叫用的回呼。

相關權限

run_container


sendEventToGoogleAnalytics

使用通用事件資料將單一事件傳送至 Google Analytics,並傳回 promise,該 promise 會解析為具有 location 鍵的物件,或拒絕為具有 reason 鍵的物件。目的地 Google Analytics 則取決於事件資料中的評估 ID。

location 欄位會設為 location 標頭 (如有)。

範例

const logToConsole = require('logToConsole');
const sendEventToGoogleAnalytics = require('sendEventToGoogleAnalytics');
const setResponseHeader = require('setResponseHeader');
const setResponseStatus = require('setResponseStatus');

// Sends an event to Google Analytics and returns failure if the request did not
// succeed. Additionally, if the request resulted in a redirect request, the
// code nominates a redirect response to be returned.
sendEventToGoogleAnalytics(event).then((response) => {
  if (response.location) {
    setResponseHeader('location', response.location);
    setResponseStatus(302);
  } else {
    setResponseStatus(200);
  }
  data.gtmOnSuccess();
}).catch((error) => {
  logToConsole(error.reason);
  setResponseStatus(500);
  data.gtmOnFailure();
});

語法

sendEventToGoogleAnalytics(event);

參數

參數 類型 說明
event 物體 採用統一結構定義格式的事件。

相關權限

需要 send_http 權限。權限設定必須至少允許存取:

  • 允許 Google 網域

sendHttpGet

向指定網址發出 HTTP GET 要求,並傳回 promise,在要求完成或逾時後解析結果。

解析結果是包含三個鍵的物件:statusCode、headers 和 body。如果要求失敗 (例如網址無效、沒有主機路徑、SSL 協商失敗等),Promise 會拒絕並傳回:{reason: 'failed'}。如果設定了 timeout 選項,且要求逾時,Promise 會拒絕並傳回:{reason: 'timed_out'}

範例

const sendHttpGet = require('sendHttpGet');

// Returns the response body as the value for a variable.
return sendHttpGet('https://example.com/item/' + data.itemId, {
  headers: {key: 'value'},
  timeout: 500,
}).then((result) => result.body, () => undefined);

語法

sendHttpGet(url[, options]);

參數

參數 類型 說明
url string 要求的網址。
options object 選用要求選項。(請參閱下方的「選項」)。

選項

選項 類型 說明
headers string 其他要求標頭。
timeout number 要求中止前的逾時時間,以毫秒為單位。預設值為 15000。
authorization object 呼叫 getGoogleAuth 時,可選擇加入授權物件,以便在向 googleapis.com 發出要求時加入授權標頭。

相關權限

send_http


sendHttpRequest

向指定網址發出 HTTP 要求,並傳回 Promise,在要求完成或逾時後,以回應解析。

解析結果是包含三個鍵的物件:statusCode、headers 和 body。如果要求失敗 (例如網址無效、沒有主機路徑、SSL 協商失敗等),Promise 會拒絕並傳回:{reason: 'failed'}。如果設定了 timeout 選項,且要求逾時,Promise 會拒絕並傳回:{reason: 'timed_out'}

範例

const sendHttpRequest = require('sendHttpRequest');
const setResponseBody = require('setResponseBody');
const setResponseHeader = require('setResponseHeader');
const setResponseStatus = require('setResponseStatus');

const postBody = 'interaction=click&campaign=promotion&medium=email';
// Sends a POST request and nominates response based on the response to the POST
// request.
sendHttpRequest('https://example.com/collect', {
  headers: {key: 'value'},
  method: 'POST',
  timeout: 500,
}, postBody).then((result) => {
  setResponseStatus(result.statusCode);
  setResponseBody(result.body);
  setResponseHeader('cache-control', result.headers['cache-control']);
});

語法

sendHttpRequest(url[, options[, body]]);

參數

參數 類型 說明
url string 要求的網址。
options object 選用要求選項。(請參閱下方的「選項」)。
body string 選用要求主體。

選項

選項 類型 說明
headers string 其他要求標頭。
method 物體 要求方法。預設值為 GET。
timeout number 要求中止前的逾時時間,以毫秒為單位。預設值為 15000。
authorization object 呼叫 getGoogleAuth 時,可選擇加入授權物件,以便在向 googleapis.com 發出要求時加入授權標頭。

相關權限

send_http


sendPixelFromBrowser

向瀏覽器傳送指令,將提供的網址載入為 <img> 標記。Google Analytics 的 Google 代碼和 Google Analytics:GA 事件網頁代碼支援這項指令通訊協定。您必須設定伺服器容器網址。詳情請參閱操作說明。

如果傳入的要求不支援指令通訊協定,或回應已清除,這個 API 會傳回 false。否則,這個 API 會傳回 true。

範例:

const sendPixelFromBrowser = require('sendPixelFromBrowser');

sendPixelFromBrowser('https://example.com/?id=123');

語法

sendPixelFromBrowser(url)

參數

參數 類型 說明
url string 要傳送至瀏覽器的網址。

相關權限

send_pixel_from_browser


setCookie

設定或刪除具有指定選項的 Cookie。

如要刪除 Cookie,必須設定與 Cookie 建立時相同的路徑和網域,並指派過去的到期值,例如 "Thu, 01 Jan 1970 00:00:00 GMT"。

請注意,您必須呼叫 returnResponse,才能將回應傳回用戶端。

範例

const setCookie = require('setCookie');

// Sets an httpOnly cookie with a max-age of 3600.
setCookie('cookieName', 'cookieValue', {'max-age': 3600, httpOnly: true});

語法

setCookie(name, value[, options[, noEncode]]);

參數

參數 類型 說明
name string Cookie 名稱。名稱不區分大小寫。
value string Cookie 值。
options 物體 選用 Cookie 屬性:domain、expires、fallbackDomain、httpOnly、max-age、path、secure 和 sameSite。(請參閱下方的「選項」一節)。
noEncode boolean 如果設為 true,系統就不會對 Cookie 值進行編碼。預設值為 false。

選項

  • domain:用來接收 Cookie 的主機。如果設為特殊值「auto」,系統會自動使用下列策略計算主機:

    • Forwarded 標頭的 eTLD+1 (如有)。
    • X-Forwarded-Host 標頭的 eTLD+1 (如有)。
    • Host 標頭的 eTLD+1。
  • expires:Cookie 的最長生命週期。這必須是世界標準時間格式的日期字串,例如「Sat, 26 Oct 1985 08:21:00 GMT」。如果同時設定 expires 和 max-age,系統會優先採用 max-age。

  • httpOnly:如果為 true,則禁止 JavaScript 存取 Cookie。

  • max-age:Cookie 效期前的秒數。如果值為零或負數,Cookie 會立即失效。如果同時設定 expires 和 max-age,系統會優先採用 max-age。

  • path:要求網址中必須存在的路徑,否則瀏覽器不會傳送 Cookie 標頭。

  • secure:如果設為 true,則只有在從 https: 端點提出要求時,Cookie 才會傳送至伺服器。

  • sameSite:斷言不得與跨源要求一併傳送 Cookie。必須是 'strict'、'lax' 或 'none'。

相關權限

set_cookie


setPixelResponse

將回應主體設為 1x1 GIF、將 Content-Type 標頭設為「image/gif」、設定快取標頭,讓使用者代理程式不會快取回應,並將回應狀態設為 200。

請注意,您必須呼叫 returnResponse,才能將回應傳回用戶端。

語法

setPixelResponse();

相關權限

需要 access_response 權限。權限必須設定為至少允許存取:

  • headers - 必須允許下列鍵
    • content-type
    • cache-control
    • expires
    • pragma
  • body
  • status

setResponseBody

將回應主體設為引數。

請注意,您必須呼叫 returnResponse,才能將回應傳回用戶端。

語法

setResponseBody(body[, encoding]);

參數

參數 類型 說明
body string 要設為回應主體的值。
encoding string 回應主體的字元編碼 (預設為 'utf8')。支援的值包括 'ascii'、'utf8'、'utf16le'、'ucs2'、'base64'、'latin1'、'binary' 和 'hex'。

相關權限

需要 access_response 權限。權限必須設定為至少允許存取:

  • body

setResponseHeader

在要傳回的回應中設定標頭。如果這個 API 先前設定過同名標頭 (不區分大小寫),後續呼叫會覆寫或清除先前呼叫端設定的值。

請注意,您必須呼叫 returnResponse,才能將回應傳回用戶端。

語法

setResponseHeader(name, value);

參數

參數 類型 說明
name string 標頭名稱。HTTP 標頭名稱不區分大小寫,因此標頭名稱會轉換為小寫。
value string undefined 標頭值。如果為空值或未定義,則會從要傳回的回應中清除指定標頭。

相關權限

需要 access_response 權限。權限必須設定為至少允許存取:

  • headers

setResponseStatus

設定要傳回的回應 HTTP 狀態碼。

請注意,您必須呼叫 returnResponse,才能將回應傳回用戶端。

語法

setResponseStatus(statusCode);

參數

參數 類型 說明
statusCode number 要傳回的 HTTP 狀態碼。

相關權限

需要 access_response 權限。權限必須設定為至少允許存取:

  • status

sha256

計算輸入內容的 SHA-256 摘要,並叫用回呼,其中摘要以 Base64 編碼,除非 options 物件指定不同的輸出編碼。

這個 API 簽章和行為與網站容器的 sha256 API 相同,但伺服器容器中的自訂範本應使用 sha256Sync API,以簡化程式碼。

範例

const encodeUriComponent = require('encodeUriComponent');
const sendHttpGet = require('sendHttpGet');
const sha256 = require('sha256');

sha256('inputString', (digest) => {
  sendHttpGet('https://example.com/collect?id=' + encodeUriComponent(digest));
});

sha256('inputString', (digest) => {
  sendHttpGet('https://example.com/collect?id=' + encodeUriComponent(digest));
}, {outputEncoding: 'hex'});

語法

sha256(input, onSuccess, options = undefined);

參數

參數 類型 說明
input string 要雜湊的字串。
onSuccess 函式 使用產生的摘要 (以 base64 編碼) 呼叫,除非 options 物件指定不同的輸出編碼。
options 物體 選用選項物件,用於指定輸出內容編碼。如果指定,物件應包含鍵 outputEncoding,值為 base64 或 hex。

相關權限

無。


sha256Sync

計算並傳回輸入內容的 SHA-256 摘要 (以 Base64 編碼),除非 options 物件指定不同的輸出編碼。

範例

const encodeUriComponent = require('encodeUriComponent');
const sendHttpGet = require('sendHttpGet');
const sha256Sync = require('sha256Sync');

const digestBase64 = sha256Sync('inputString');
const digestHex = sha256Sync('inputString', {outputEncoding: 'hex'});
sendHttpGet('https://example.com/collect?id=' + encodeUriComponent(digestBase64));
sendHttpGet('https://example.com/collect?id=' + encodeUriComponent(digestHex));

語法

sha256Sync(input, options = undefined);

參數

參數 類型 說明
input string 要雜湊的字串。
options 物體 選用選項物件,用於指定輸出內容編碼。如果指定,物件應包含鍵 outputEncoding,值為 base64 或 hex。

相關權限

無。


templateDataStorage

傳回含有範本資料儲存庫存取方法的物件。範本資料儲存庫可讓資料在單一範本的執行作業之間共用。儲存在範本資料儲存庫中的資料會保留在執行容器的伺服器上。在多數情況下,有多個伺服器會執行容器,因此將資料儲存在範本資料儲存庫中,不保證每個後續要求都能存取資料。

「templateDataStorage」名稱中的「data」是指只能使用這個 API 儲存一般、非函式資料類型。傳遞至 API 的任何函式或函式參照,都會改為儲存為 null。

語法

const templateDataStorage = require('templateDataStorage');

// Returns a copy of the value stored for the given key, or null if nothing
// is stored with that key.
templateDataStorage.getItemCopy(key);

// Stores a copy of the value for the given key (or removes the data stored
// for the given key if the input value is null).
templateDataStorage.setItemCopy(key, value);

// Removes the value stored for the given key, if present.
templateDataStorage.removeItem(key);

// Deletes all values stored for the current template.
templateDataStorage.clear();

範例

const sendHttpGet = require('sendHttpGet');
const setResponseBody = require('setResponseBody');
const setResponseStatus = require('setResponseStatus');
const templateDataStorage = require('templateDataStorage');

// Check to see if the item is in the cache.
const cachedBody = templateDataStorage.getItemCopy(data.key);
if (cachedBody) {
  setResponseBody(cachedBody);
  data.gtmOnSuccess();
  return;
}

sendHttpGet(data.url).then((result) => {
  if (result.statusCode >= 200 && result.statusCode < 300) {
    setResponseBody(result.body);
    templateDataStorage.setItemCopy(data.key, result.body);
    data.gtmOnSuccess();
  } else {
    data.gtmOnFailure();
  }
  setResponseStatus(result.statusCode);
});

相關權限

access_template_storage


testRegex

根據透過 createRegex API 建立的規則運算式測試字串。如果規則運算式相符,則傳回 true。否則傳回 false。

使用全域旗標建立的規則運算式是有狀態的。詳情請參閱 RegExp 說明文件。

範例

const createRegex = require('createRegex');
const testRegex = require('testRegex');

const domainRegex = createRegex('\\w+\\.com', 'i');

// createRegex returns null if the regex is invalid or Re2 is not available.
if (domainRegex === null) return;

// Returns true
testRegex(domainRegex, 'example.com/foobar');

語法

testRegex(regex, string);

參數

參數 類型 說明
regex 物件 要測試的規則運算式,由 createRegex API 傳回。
string string 測試字串。

相關權限

無。


toBase64

將字串編碼為 base64 或 base64url。預設為 Base64 編碼。

語法

toBase64(input, options);

參數

參數 類型 說明
input string 要編碼的字串。
options object 選用 API 設定。(請參閱下方的「選項」)。

選項

選項 類型 說明 最低版本
urlEncoding boolean 如果為 true,結果會使用 base64url 格式編碼。 1.0.0

範例

const toBase64 = require('toBase64');

const base64Hello = toBase64('hello');
const base64UrlHello = toBase64('hello', {urlEncoding: true});

相關權限

無。


BigQuery

傳回提供 BigQuery 函式的物件。

BigQuery.insert 函式可將資料寫入 BigQuery 資料表。這個方法會傳回 Promise,在插入成功時解析,或在發生錯誤時拒絕。

插入成功時,promise 會解析,不含任何引數。

如果插入失敗,Promise 會拒絕,並傳回物件清單,其中包含錯誤原因,以及可能發生的錯誤資料列物件。要求可能部分成功,部分失敗。在這種情況下,系統會拒絕承諾,並列出每個資料列的錯誤清單,以及資料列物件,協助區分哪些資料列已插入 (請參閱下方的錯誤範例)。詳情請參閱 BigQuery 的錯誤訊息說明文件。

語法

BigQuery.insert(connectionInfo, rows[, options]);

參數

參數 類型 說明
connectionInfo 物體 定義連結至 BigQuery 資料表所需的資訊。其中有一個選用參數和兩個必要參數:
  • projectId - 選用 Google Cloud Platform 專案 ID。如果省略,只要專案 ID 的 access_bigquery 權限設定設為 * 或 GOOGLE_CLOUD_PROJECT,系統就會從環境變數 GOOGLE_CLOUD_PROJECT 擷取 projectId。如果伺服器容器是在 Google Cloud 上執行,GOOGLE_CLOUD_PROJECT 會設為 Google Cloud 雲端專案 ID。
  • datasetId:BigQuery 資料集 ID。
  • tableId:BigQuery 資料表 ID。
rows 陣列 要插入資料表的資料列。
options 物體 選用要求選項。支援的選項包括:ignoreUnknownValues 和 skipInvalidRows。系統會忽略不明的選項鍵。(請參閱下方的「選項」一節)。

選項

參數 類型 說明
ignoreUnknownValues boolean 如果設為 true,則接受所含值不符合結構定義的資料列。系統會忽略不明的值。預設為 false。
skipInvalidRows boolean 如果設為 true,則即使存在無效資料列,也會插入要求的所有有效資料列。預設為 false。

錯誤範例

如果出現「找不到模組」錯誤,表示伺服器容器可能執行舊版映像檔,尚未包含 BigQuery 模組。請使用部署指令碼,以相同設定重新部署伺服器容器。作業完成後,系統會自動加入模組。

非插入錯誤通常有一個錯誤物件,其中包含 reason 鍵:

[{reason: 'invalid'}]

插入錯誤可能包含多個錯誤物件,其中有 errors 陣列和 row 物件。以下是插入兩個資料列時,只有一個資料列發生錯誤的回應範例:

[
  {
    "errors": [
      {
        "reason":"invalid"
      }
    ],
    "row": {
      "string_col":"otherString",
      "number_col":-3,
      "bool_col":3
    }
  },
  {
    "errors": [
      {
        "reason":"stopped"
      }
    ],
    "row": {
      "string_col":"stringValue",
      "number_col":5,
      "bool_col:false
    }
  }
]

範例

const BigQuery = require('BigQuery');

const connectionInfo = {
  'projectId': 'gcp-cloud-project-id',
  'datasetId': 'destination-dataset',
  'tableId': 'destination-table',
};

const rows = [{
  'column1': 'String1',
  'column2': 1234,
}];

const options = {
  'ignoreUnknownValues': true,
  'skipInvalidRows': false,
};

BigQuery.insert(connectionInfo, rows, options)
  .then(data.gtmOnSuccess, data.gtmOnFailure);

相關權限

access_bigquery


Firestore

傳回提供 Firestore 函式的物件。

這個 API 僅支援原生模式的 Firestore,不支援 Datastore 模式的 Firestore。此外,API 僅支援使用預設資料庫。

Firestore.read

Firestore.read 函式會從 Firestore 文件讀取資料,並傳回 Promise,解析為包含兩個鍵的物件:id 和 data。如果文件不存在,Promise 會拒絕,並傳回包含 reason 鍵 (等於 not_found) 的物件。

語法

Firestore.read(path[, options]);

參數

參數 類型 說明
path string 文件或集合的路徑。開頭或結尾不得為「/」。
options 物體 選用要求選項。支援的選項包括:projectId、disableCache 和 transaction。系統會忽略不明的選項索引鍵。(請參閱下方的「選項」一節)。

選項

參數 類型 說明
projectId string (選用) Google Cloud Platform 專案 ID。如果省略,只要專案 ID 的 access_firestore 權限設定設為 * 或 GOOGLE_CLOUD_PROJECT,系統就會從環境變數 GOOGLE_CLOUD_PROJECT 擷取 projectId。如果伺服器容器是在 Google Cloud 上執行,GOOGLE_CLOUD_PROJECT 會設為 Google Cloud 專案 ID。
disableCache boolean (選用) 決定是否停用快取。 快取功能預設為啟用,會在要求期間快取結果。
transaction string (選用) 從 Firestore.runTransaction() 擷取的值。標示要在交易中使用的作業。

範例

const Firestore = require('Firestore');

return Firestore.read('collection/document', {
  projectId: 'gcp-cloud-project-id',
}).then((result) => result.data.key, () => undefined);

Firestore.write

Firestore.write 函式會將資料寫入 Firestore 文件或集合。若是集合的路徑,系統會建立文件,並隨機產生 ID。如果路徑指向文件,但文件不存在,系統會建立文件。這個 API 會傳回承諾,解析為新增或修改的文件 ID。如果使用交易選項,API 仍會傳回 Promise,但不會包含 ID,因為寫入作業會批次處理。

語法

Firestore.write(path, input[, options]);

參數

參數 類型 說明
path string 文件或集合的路徑。開頭或結尾不得為「/」。
input 物體 要寫入文件的值。如果設定合併選項,API 會將輸入內容中的鍵合併至文件。
options 物體 選用要求選項。支援的選項包括:projectId、merge 和 transaction。系統會忽略不明的選項鍵。(請參閱下方的「選項」一節)。

選項

參數 類型 說明
projectId string (選用) Google Cloud Platform 專案 ID。如果省略,只要專案 ID 的 access_firestore 權限設定設為 * 或 GOOGLE_CLOUD_PROJECT,系統就會從環境變數 GOOGLE_CLOUD_PROJECT 擷取 projectId。如果伺服器容器是在 Google Cloud 上執行,GOOGLE_CLOUD_PROJECT 會設為 Google Cloud 專案 ID。
merge boolean (選用) 如果設為 true,則會將輸入內容中的鍵合併至文件,否則這個方法會覆寫整份文件。預設值為 false。
transaction string (選用) 從 Firestore.runTransaction() 擷取的值。標示要在交易中使用的作業。

範例

const Firestore = require('Firestore');

const input = {key1: 'value1', key2: 12345};

Firestore.write('collection/document', input, {
  projectId: 'gcp-cloud-project-id',
  merge: true,
}).then((id) => {
  data.gtmOnSuccess();
}, data.gtmOnFailure);

Firestore.query

Firestore.query 函式會查詢指定的集合,並傳回一個 Promise,這個 Promise 會解析為符合查詢條件的 Firestore 文件陣列。Firestore 文件物件與 Firestore.read 中列出的物件相同。如果沒有符合查詢條件的文件,傳回的 Promise 會解析為空白陣列。

語法

Firestore.query(collection, queryConditions[, options]);

參數

參數 類型 說明
collection string 集合的路徑。開頭或結尾不得為「/」。
queryConditions 陣列 查詢條件陣列。每項查詢都採用陣列形式,包含三個值:key、operator 和 expectedValue。E.g.: [[‘id’, ‘<’, ‘5’], [‘state’, ‘==’, ‘CA’]]。

系統會將條件與 AND 運算子結合,建立查詢結果。如需相容查詢運算子的清單,請參閱 Firestore 的查詢運算子。
options 物體 選用要求選項。支援的選項包括:projectId、disableCache、limit 和 transaction。系統會忽略不明的選項鍵。(請參閱下方的「選項」一節)。

選項

參數 類型 說明
projectId string (選用) Google Cloud Platform 專案 ID。如果省略,只要專案 ID 的 access_firestore 權限設定設為 * 或 GOOGLE_CLOUD_PROJECT,系統就會從環境變數 GOOGLE_CLOUD_PROJECT 擷取 projectId。如果伺服器容器是在 Google Cloud 上執行,GOOGLE_CLOUD_PROJECT 會設為 Google Cloud 專案 ID。
disableCache boolean (選用) 決定是否停用快取。快取功能預設為啟用,會在要求期間快取結果。
limit number (選用) 變更查詢傳回的結果數量上限,預設值為 5。
transaction string (選用) 從 Firestore.runTransaction() 擷取的值。標示要在交易中使用的作業。

範例

const Firestore = require('Firestore');

const queries = const queries = [['id', '==', '5']];

return Firestore.query('collection', queries, {
  projectId: 'gcp-cloud-project-id',
  limit: 1,
}).then((documents) => documents[0].data.key, () => undefined);

Firestore.runTransaction

使用者可透過 Firestore.runTransaction 函式,以不可分割的方式讀取及寫入 Firestore。如果發生並行寫入或其他交易衝突,系統最多會重試兩次交易。如果嘗試三次後仍失敗,API 會拒絕並傳回錯誤。如果交易成功,這個 API 會傳回一個 promise,解析為每個寫入作業的文件 ID 陣列;如果失敗,則會拒絕並傳回錯誤。

語法

Firestore.runTransaction(callback[, options]);

參數

參數 類型 說明
callback 函式 使用字串交易 ID 叫用的回呼。交易 ID 可傳遞至讀取/寫入/查詢 API 呼叫。這個回呼函式「必須」傳回 Promise。 回呼最多可執行三次,之後就會失敗。
options 物體 選用要求選項。唯一支援的選項是 projectId。系統會忽略不明的選項鍵。(請參閱下方的「選項」一節)。

選項

參數 類型 說明
projectId string (選用) Google Cloud Platform 專案 ID。如果省略,只要專案 ID 的 access_firestore 權限設定設為 * 或 GOOGLE_CLOUD_PROJECT,系統就會從環境變數 GOOGLE_CLOUD_PROJECT 擷取 projectId。如果伺服器容器是在 Google Cloud 上執行,GOOGLE_CLOUD_PROJECT 會設為 Google Cloud 專案 ID。

範例

const Firestore = require('Firestore');

const path = 'collection/document';
const projectId = 'gcp-cloud-project-id';

Firestore.runTransaction((transaction) => {
  const transactionOptions = {
    projectId: projectId,
    transaction: transaction,
  };
  // Must return a promise.
  return Firestore.read(path, transactionOptions).then((result) => {
    const newInputCount = result.data.inputCount + 1;
    const input = {key1: 'value1', inputCount: newInputCount};
    return Firestore.write(path, input, transactionOptions);
  });
}, {
  projectId: projectId
}).then((ids) => {
  data.gtmOnSuccess();
}, data.gtmOnFailure);

錯誤範例

每個 Firestore 函式都會傳回錯誤,並拒絕包含 reason 鍵的物件:

Firestore.read(...).then(onSuccess, (error) => {
  if (error.reason === 'unknown') {
    // Handle the unknown error here.
  }
});

錯誤原因可能包含但不限於 Firestore REST API 錯誤代碼。

相關權限

access_firestore


JSON

傳回提供 JSON 函式的物件。

parse() 函式會剖析 JSON 字串,建構字串描述的值或物件。如果無法剖析值 (例如 JSON 格式錯誤),函式會傳回 undefined。如果輸入值不是字串,系統會強制將輸入內容轉換為字串。

stringify() 函式會將輸入內容轉換為 JSON 字串。如果無法剖析值 (例如物件有循環),方法會傳回 undefined。

範例

const JSON = require('JSON');

// The JSON input string is converted to an object.
const object = JSON.parse('{"foo":"bar"}');

// The input object is converted to a JSON string.
const str = JSON.stringify({foo: 'bar'});

語法

JSON.parse(stringInput);
JSON.stringify(value);

相關權限

無。


Math

提供 Math 函式的物件。

語法

const Math = require('Math');

// Retrieve the absolute value.
const absolute = Math.abs(-3);

// Round the input down to the nearest integer.
const roundedDown = Math.floor(3.6);

// Round the input up to the nearest integer.
const roundedUp = Math.ceil(2.2);

// Round the input to the nearest integer.
const rounded = Math.round(3.1);

// Return the largest argument.
const biggest = Math.max(1, 3);

// Return the smallest argument.
const smallest = Math.min(3, 5);

// Return the first argument raised to the power of the second argument.
const powerful = Math.pow(3, 1);

// Return the square root of the argument.
const unsquared = Math.sqrt(9);

參數

數學函式參數會轉換為數字。

相關權限

無。


Messages

下列 API 可搭配運作,在容器的不同部分之間傳遞訊息。


addMessageListener

新增函式,用於監聽特定類型的訊息。使用 sendMessage API 傳送該類型的訊息時 (通常由代碼傳送),回呼會同步執行。回呼會使用兩個參數執行:

  1. messageType:string
  2. message:Object

如果在用戶端中新增回呼,回呼會接收該用戶端建立的所有事件訊息。如果回呼應只接收特定事件的訊息,請在 runContainer API 的 onStart 函式中使用 bindToEvent,將這個 API 繫結至該事件。請參閱範例。

語法

const addMessageListener = require('addMessageListener');

addMessageListener('send_pixel', (messageType, message) => {
  // This will be run whenever something sends a 'send_pixel' message.
});

參數

參數 類型 說明
messageType string 要監聽的訊息類型。如果值不是字串,系統會強制轉型為字串。
callback 函式 傳送適用訊息類型的訊息時,要執行的回呼。如果回呼不是函式,API 就不會執行任何動作。

範例

const addMessageListener = require('addMessageListener');
const claimRequest = require('claimRequest');
const extractEventsFromMpv1 = require('extractEventsFromMpv1');
const returnResponse = require('returnResponse');
const runContainer = require('runContainer');

claimRequest();
addMessageListener('send_pixel', (messageType, message) => {
  // This will be run whenever a tag sends a 'send_pixel' message.
});

const events = extractEventsFromMpv1();
let eventsCompleted = 0;
events.forEach((event, i) => {
  runContainer(events[i], /* onComplete= */ () => {
    if (events.length === ++eventsCompleted) {
      returnResponse();
    }
  }, /* onStart= */ (bindToEvent) => {
    if (i === 0) {
      bindToEvent(addMessageListener)('send_pixel', (messageType, message) => {
        // This will be called whenever a tag for the first event sends a
        // 'send_pixel' message.
      });
    }
  });
});

相關權限

需要 use_message 權限。權限設定必須至少允許:

  • Usage 為 listen 或 listen_and_send 的訊息類型。

hasMessageListener

如果已為指定訊息類型新增訊息事件監聽器,則傳回 true。否則傳回 false。

語法

const hasMessageListener = require('hasMessageListener');

hasMessageListener('send_pixel');

相關權限

無。


sendMessage

將指定類型的訊息傳送給已註冊的事件監聽器。這可用於將訊息從代碼傳回執行容器的用戶端。

語法

const sendMessage = require('sendMessage');

sendMessage('send_pixel', {url: 'https://analytics.example.com/collect'});

參數

參數 類型 說明
messageType string 要傳送的訊息類型。如果值不是字串,系統會強制轉型為字串。
message 物體 要傳送的訊息。如果訊息不是物件,API 就不會執行任何動作。

相關權限

需要 use_message 權限。權限設定必須至少允許:

  • Usage 為 listen_and_send 或 send 的訊息類型。

Object

傳回提供 Object 方法的物件。

keys() 方法提供標準程式庫 Object.keys() 行為。它會傳回指定物件本身可列舉屬性名稱的陣列,順序與 for...in... 迴圈相同。如果輸入值不是物件,則會強制轉型為物件。

values() 方法提供標準程式庫 Object.values() 行為。它會以 for...in... 迴圈的相同順序,傳回指定物件本身可列舉屬性值的陣列。如果輸入值不是物件,則會強制轉型為物件。

entries() 方法提供標準程式庫 Object.entries() 行為。這個方法會傳回指定物件本身可列舉屬性 [key, value] 配對的陣列,順序與 for...in... 迴圈相同。如果輸入值不是物件,則會強制轉型為物件。

freeze() 方法提供標準程式庫 Object.freeze() 行為。凍結的物件無法再變更;凍結物件可防止新增屬性、移除現有屬性,以及變更現有屬性的值。freeze() 會傳回傳入的相同物件。原始或空值引數會視為凍結物件,並傳回。

delete() 方法提供標準程式庫刪除運算子行為。除非物件已凍結,否則會從物件中移除指定鍵。與標準程式庫刪除運算子一樣,如果第一個輸入值 (objectInput) 是未凍結的物件,即使第二個輸入值 (keyToDelete) 指定的鍵不存在,也會傳回 true。在所有其他情況下,則會傳回 false。不過,它與標準程式庫刪除運算子的差異如下:

  • 「keyToDelete」不得為指定巢狀鍵的點分隔字串。
  • delete() 無法用於從陣列中移除元素。
  • delete() 無法用於從全域範圍移除任何屬性。

語法

Object.keys(objectInput)
Object.values(objectInput)
Object.entries(objectInput)
Object.freeze(objectInput)
Object.delete(objectInput, keyToDelete)

參數

Object.keys

參數 類型 說明
objectInput any 要列舉鍵的物件。如果輸入內容不是物件,則會強制轉型為物件。

Object.values

參數 類型 說明
objectInput any 要列舉值的物件。如果輸入內容不是物件,則會強制轉型為物件。

Object.entries

參數 類型 說明
objectInput any 要列舉鍵/值組合的物件。如果輸入內容不是物件,則會強制轉型為物件。

Object.freeze

參數 類型 說明
objectInput any 要凍結的物件。如果輸入內容不是物件,系統會將其視為凍結物件。

Object.delete

參數 類型 說明
objectInput any 要刪除金鑰的物件。
keyToDelete string 要刪除的頂層鍵。

範例

const Object = require('Object');

// The keys of an object are enumerated in an array.
const keys = Object.keys({foo: 'bar'});

// The values of an object are enumerated in an array.
const values = Object.values({foo: 'bar'});

// The key/value pairs of an object are enumerated in an array.
const entries = Object.entries({foo: 'bar'});

// The input object is frozen.
const frozen = Object.freeze({foo: 'bar'});

// The key is removed from the input object.
const obj1 = {deleteme: 'value'};
Object.delete(obj1, 'deleteme');
// Only a top-level key can be specified as the key to delete.
const obj2 = {nested: {key: 'value'}};
Object.delete(obj2, 'nested.key'); // This has no effect.
Object.delete(obj2.nested, 'key'); // This deletes the nested key.

Promise

傳回提供與 Promise 互動方法的物件。

Promise 的功能與 JavaScript Promise 相同。每個執行個體都有三個方法,會傳回 Promise,以便在 Promise 結算時採取進一步行動:

  • .then():處理已解決和遭拒的案件。這個方法會採用兩個回呼做為參數:一個用於成功案例,另一個用於失敗案例。
  • .catch():只處理遭拒案件。採用一個回呼做為參數。
  • .finally():無論 Promise 是已解析或遭拒,都能執行程式碼。接受一個回呼做為參數,叫用時不含引數。

傳回 Promise 的變數等於 Promise 的解析值,如果 Promise 拒絕,則為 false。

範例

promise.then((resolvedValue) => {
    // Handles when promise resolves.
  }, (rejectedValue) => {
    // Handles when promise rejects.
  });
promise.catch((rejectedValue) => {
    // Handles when promise rejects.
  });
promise.finally(() => {
    // Runs regardless of whether or not the previous promise resolves or
    // rejects.
  });

Promise.all

傳回承諾,可能為:

  • 在所有輸入內容都解析完畢時解析,或
  • 只要有任何輸入內容遭拒,就會拒絕

語法

Promise.all(inputs);

參數

參數 類型 說明
inputs 陣列 值或 Promise 的陣列。如果輸入內容不是 Promise,系統會將其視為 Promise 的解析值傳遞。如果輸入內容不是陣列,則會擲回錯誤。

範例

const Promise = require('Promise');
const sendHttpGet = require('sendHttpGet');

return Promise.all(['a', sendHttpGet('https://example.com')])
  .then((results) => {
    // results will equal: ['a', {statusCode: 200, headers: {}, body: ''}]
  });

相關權限

無。

Promise.create

建立功能與 JavaScript Promise 相同的 Promise。

語法

Promise.create(resolver);

參數

參數 類型 說明
resolver 函式 使用兩個函式 (resolve 和 reject) 叫用的函式。 叫用對應的參數時,傳回的 Promise 會解析或拒絕。如果解析器不是函式,則會擲回錯誤。

範例

const Promise = require('Promise');

return Promise.create((resolve, reject) => {
  // Do asynchronous work that eventually calls resolve() or reject()
});

相關權限

無。

測試 API

這些 API 會與沙箱 JavaScript 測試搭配使用,在 Google 代碼管理工具中建立自訂範本測試。這些測試 API 不需要 require() 陳述式。[進一步瞭解自訂範本測試]。


assertApi

傳回比對器物件,可用於流暢地對指定 API 做出斷言。

語法

assertApi(apiName)

參數

參數 類型 說明
apiName string 要檢查的 API 名稱;與傳遞至 require() 的字串相同。

比對器

  • Subject.wasCalled()
  • Subject.wasNotCalled()
  • Subject.wasCalledWith(...expected)
  • Subject.wasNotCalledWith(...expected)

範例

assertApi('sendPixel').wasCalled();
assertApi('getUrl').wasNotCalled();
assertApi('makeNumber').wasCalledWith('8');
assertApi('setInWindow').wasNotCalledWith('myVar', 'theWrongValue');

assertThat

assertThat API 是以 Google 的 [Truth] 程式庫為模型。它會傳回一個物件,可用於流暢地對主體的值進行斷言。斷言失敗會立即停止測試,並將測試標示為失敗。不過,某項測試失敗不會影響其他測試案例。

語法

assertThat(actual, opt_message)

參數

參數 類型 說明
actual any 要在流暢檢查中使用的值。
opt_message string 斷言失敗時要輸出的訊息 (選用)。

比對器

Matcher 說明
isUndefined() 判斷主體是否為 undefined。
isDefined() 宣告主體不是 undefined。
isNull() 宣告主體為 null。
isNotNull() 宣告主體不是 null。
isFalse() 判斷主體是否為 false。
isTrue() 宣告主體為 true。
isFalsy() 判斷主體是否為 falsy。Falsy 值為 undefined、null、false、NaN、0 和 '' (空白字串)。
isTruthy() 宣告主體為 truthy。Falsy 值為 undefined、null、false、NaN、0 和 '' (空白字串)。
isNaN() 斷言主體的值為 NaN。
isNotNaN() 宣告主體為 NaN 以外的任何值。
isInfinity() 斷言主體為正無限大或負無限大。
isNotInfinity() 斷言主體是正負無限大以外的任何值。
isEqualTo(expected) 宣告主體等於指定值。這是值比較,而非參照比較。系統會以遞迴方式比較物件和陣列的內容。
isNotEqualTo(expected) 聲明主體不等於指定值。這是值比較,而非參照比較。系統會以遞迴方式比較物件和陣列的內容。
isAnyOf(...expected) 宣告主體等於其中一個指定值。這是值比較,而非參照比較。系統會以遞迴方式比較物件和陣列的內容。
isNoneOf(...expected) 聲明主體不等於任何指定值。這是值比較,而非參照比較。系統會以遞迴方式比較物件和陣列的內容。
isStrictlyEqualTo(expected) 斷言主體與指定值完全相等 (===)。
isNotStrictlyEqualTo(expected) 判斷主體是否不嚴格等於 (!==) 指定值。
isGreaterThan(expected) 在排序比較中,斷言主體大於 (>) 指定值。
isGreaterThanOrEqualTo(expected) 在排序比較中,斷言主體大於或等於 (>=) 指定值。
isLessThan(expected) 在排序比較中,斷言主體小於 (<) 指定值。
isLessThanOrEqualTo(expected) 在排序比較中,判斷主體是否小於或等於 (<=) 指定值。
contains(...expected) 斷言主體是陣列或字串,其中包含所有指定值 (不限順序)。這是值比較,而非參照比較。系統會遞迴比較物件和陣列的內容。
doesNotContain(...expected) 斷言主體是不含任何指定值的陣列或字串。這是值比較,而非參照比較。 系統會遞迴比較物件和陣列的內容。
containsExactly(...expected) 斷言主體是包含所有指定值 (不限順序) 且不含其他值的陣列。這是值比較,而非參照比較。系統會遞迴比較物件和陣列的內容。
doesNotContainExactly(...expected) 斷言主體是陣列,且包含與指定值不同的一組值 (不限順序)。這是值比較,而非參照比較。系統會以遞迴方式比較物件和陣列的內容。
hasLength(expected) 斷言主體是具有指定長度的陣列或字串。如果值不是陣列或字串,則斷言一律會失敗。
isEmpty() 宣告主體為空白陣列或字串 (長度 = 0)。如果值不是陣列或字串,則斷言一律會失敗。
isNotEmpty() 宣告主體為非空陣列或字串 (長度 > 0)。如果值不是陣列或字串,斷言一律會失敗。
isArray() 宣告主體的類型為陣列。
isBoolean() 宣告主體的類型為布林值。
isFunction() 宣告主體的類型為函式。
isNumber() 宣告主體的類型為數字。
isObject() 宣告主體的類型為物件。
isString() 宣告主體的類型為字串。

範例

assertThat(undefined).isUndefined();
assertThat(id, 'ID must be defined').isDefined();
assertThat(null).isNull();
assertThat(undefined).isNotNull();
assertThat(true).isTrue();
assertThat(false).isFalse();
assertThat(1).isTruthy();
assertThat('').isFalsy();
assertThat(1/0).isInfinity();
assertThat(0).isNotInfinity();
assertThat(-'foo').isNaN();
assertThat(100).isNotNaN();
assertThat(sentUrl).isEqualTo('https://endpoint.example.com/?account=12345');
assertThat(category).isNotEqualTo('premium');
assertThat(5).isAnyOf(1, 2, 3, 4, 5);
assertThat(42).isNoneOf('the question', undefined, 41.9);
assertThat('value').isStrictlyEqualTo('value');
assertThat('4').isNotStrictlyEqualTo(4);
assertThat(['a', 'b', 'c']).contains('a', 'c');
assertThat(['x', 'y', 'z']).doesNotContain('f');
assertThat(['1', '2', '3']).containsExactly('3', '2', '1');
assertThat(['4', '5']).doesNotContainExactly('4');
assertThat('a string').hasLength(8);
assertThat([]).isEmpty();
assertThat('another string').isNotEmpty();

fail

立即失敗目前的測試,並列印指定的訊息 (如有提供)。

語法

fail(opt_message);

參數

參數 類型 說明
opt_message string 選用的錯誤訊息文字。

範例

fail('This test has failed.');

mock

mock API 可讓您覆寫沙箱化 API 的行為。模擬 API 可安全地用於範本程式碼,但只能在測試模式下運作。每次執行測試前,模擬物件都會重設。

語法

mock(apiName, returnValue);

參數

參數 類型 說明
apiName string 要模擬的 API 名稱;與傳遞至 require() 的字串相同
returnValue any API 傳回的值,或取代 API 呼叫的函式。如果 returnValue 是函式,系統會呼叫該函式來取代沙箱化 API;如果 returnValue 不是函式,系統會傳回該值來取代沙箱化 API。

範例

mock('encodeUri', "https://endpoint.example.com/?account=12345");
mock('sendPixel', function(url, onSuccess, onFailure) {
    onSuccess();
});

mockObject

mockObject API 可讓您覆寫沙箱化 API 傳回物件的行為。在範本程式碼中使用 API 是安全的,但只有在測試模式下才能運作。每次執行測試前,模擬物件都會重設。

語法

mockObject(apiName, objectMock);

參數

參數 類型 說明
apiName string 要模擬的 API 名稱;與傳遞至 require() 的字串相同
objectMock 物體 API 傳回的值,或取代 API 呼叫的函式。必須是物件。

範例

const storage = {};
let firestoreId = 1;

function asTestPromise(result) {
  return {
    then: (callback) => callback(result)
  };
}

mockObject('Firestore', {
  write: (collection, input) => {
    storage[collection + '/' + (++firestoreId)] = input;
    return asTestPromise(firestoreId);
  },
  read: (document) => asTestPromise({data: storage[document]})
});

runCode

在目前的測試環境中,使用指定的輸入資料物件執行範本的程式碼,也就是「程式碼」分頁的內容。

語法

runCode(data)

參數

參數 類型 說明
data 物體 測試中使用的資料物件。

傳回值

傳回變數範本的變數值;所有其他範本類型則傳回 undefined。

範例

runCode({field1: 123, field2: 'value'});