本文档简要介绍了适用于服务器端代码植入的 API。
addEventCallback
用于注册要在事件结束时调用的回调函数。如果该事件的所有代码都已执行完毕,系统就会调用回调函数。系统会向该回调函数传递两个值:调用该函数的容器的 ID 和包含事件相关信息的对象。
在代码中使用此 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.
});
相关权限
callLater
安排函数调用以异步方式进行。将在当前代码返回后调用该函数。等效于 setTimeout(<function>, 0)
。
示例
const callLater = require('callLater');
const logToConsole = require('logToConsole');
callLater(() => {
logToConsole('Logged asynchronously');
});
语法
callLater(function)
参数
参数 | 类型 | 说明 |
---|---|---|
function |
函数 | 要调用的函数。 |
相关权限
无。
claimRequest
在客户端中使用此 API 来声明请求。声明请求后,容器便不会运行其他客户端。
如果在代码或变量中调用此 API,它会抛出异常。如果在客户端返回后调用此 API,它会抛出异常(例如,在 callLater
或 runContainer
onComplete
函数等异步回调函数中调用)。
客户端应先使用此 API 声明请求,然后再调用 runContainer
API。
示例
const claimRequest = require('claimRequest');
claimRequest();
语法
claimRequest();
相关权限
无。
computeEffectiveTldPlusOne
返回指定网域或网址的有效顶级域名 + 1 (eTLD+1)。eTLD+1 是通过根据公共后缀列表规则评估网域计算得出的。eTLD+1 通常是您可以在其上设置 Cookie 的最高一级网域。
如果参数为 null 或未定义,则原样返回参数值。否则,参数将强制转换为字符串。如果参数不是有效的网域或网址,则返回空字符串。如果服务器无法提取公共后缀列表,则原样返回参数值。
示例
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 |
字符串 | 供计算 eTLD+1 用的网域或网址。 |
相关权限
无。
decodeUri
对提供的 URI 中的任何编码字符进行解码。返回值的类型为字符串,表示所提供的 URI 解码后的形式。如果提供的输入无效,它会返回 undefined
。
示例
const decodeUri = require('decodeUri');
const decodedUrl = decodeUri(data.encodedUrl);
if (decodedUrl) {
// ...
}
语法
decodeUri(encoded_uri);
参数
参数 | 类型 | 说明 |
---|---|---|
encoded_uri |
字符串 |
已通过 encodeUri() 或其他方式编码的 URI。
|
相关权限
无。
decodeUriComponent
对提供的 URI 组成部分中的任何编码字符进行解码。返回值的类型为字符串,表示所提供的 URI 组成部分解码后的形式。如果指定输入无效,则返回 undefined
。
示例
const decodeUriComponent = require('decodeUriComponent');
const decodedQuery = decodeUriComponent(data.query);
if (decodedQuery) {
// ...
}
语法
decodeUriComponent(encoded_uri_component);
参数
参数 | 类型 | 说明 |
---|---|---|
encoded_uri_component |
字符串 |
已通过 encodeUriComponent() 或其他方式编码的 URI 组成部分。
|
相关权限
无。
encodeUri
通过对特殊字符进行转义,返回经过编码的统一资源标识符 (URI)。返回值的类型为字符串,表示所提供的字符串编码为 URI 后的形式。
示例
const encodeUri = require('encodeUri');
const sendHttpGet = require('sendHttpGet');
sendHttpGet('https://www.example.com/' + encodeUri(pathInput));
语法
encodeUri(uri);
参数
参数 | 类型 | 说明 |
---|---|---|
uri |
字符串 | 完整的 URI。 |
相关权限
无。
encodeUriComponent
通过对特殊字符进行转义,返回经过编码的统一资源标识符 (URI)。返回值的类型为字符串,表示所提供的字符串编码为 URI 后的形式。
示例
const encodeUriComponent = require('encodeUriComponent');
const sendHttpGet = require('sendHttpGet');
sendHttpGet('https://www.example.com/?' + encodeUriComponent(queryInput));
语法
encodeUriComponent(str);
参数
参数 | 类型 | 说明 |
---|---|---|
str |
字符串 | URI 的一个组成部分。 |
相关权限
无。
extractEventsFromMpv1
将传入的 Measurement Protocol V1 请求转换为采用统一架构格式的事件列表。返回提取的事件列表。如果请求的格式不正确,则会抛出错误。
示例
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 |
字符串 | 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 |
数值 | 所返回的整数的下限值(含此值)。 |
max |
数值 | 所返回的整数的上限值(含此值)。 |
相关权限
无。
getAllEventData
返回事件数据的副本。
语法
getAllEventData();
相关权限
getClientName
返回一个字符串,其中包含当前客户端的名称。
语法
getClientName();
相关权限
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();
相关权限
getCookieValues
返回一个数组,其中包含具有指定名称的所有 Cookie 的值。
示例
const getCookieValues = require('getCookieValues');
const lastVisit = getCookieValues('lastVisit')[0];
if (lastVisit) {
// ...
}
语法
getCookieValues(name[, noDecode]);
参数
参数 | 类型 | 说明 |
---|---|---|
name |
字符串 | Cookie 的名称。 |
noDecode |
布尔值 |
如果值为 true ,则在返回 Cookie 值之前不会对其进行解码。默认值为 false 。
|
相关权限
getEventData
返回事件数据中指定路径上的值的副本。如果没有事件数据或者指定路径上没有任何值,则返回 undefined
。
示例
const getEventData = require('getEventData');
const campaignId = getEventData('campaign.id');
const itemId = getEventData('items.0.id');
const referrer = getEventData('page_referrer');
参数
参数 | 类型 | 说明 |
---|---|---|
keyPath |
任意类型 |
键的路径,其中路径组成部分以点号分隔。路径组成部分可以是对象中的键,也可以是数组中的索引。如果 keyPath 不是字符串,系统会将其强制转换为字符串。
|
语法
getEventData(keyPath);
相关权限
getGoogleScript
从一组预定的 Google 脚本中检索资源,并使用脚本及相关联的缓存元数据调用提供的回调函数。
元数据对象将基于资源响应标头包含以下缓存元数据;每个字段仅会在资源响应中包含相应标头时显示。
{
'cache-control': string,
'expires': string,
'last-modified': string,
}
示例
const getGoogleScript = require('getGoogleScript');
getGoogleScript('ANALYTICS', (script, metadata) => {
// Operate on script and metadata here.
});
语法
getGoogleScript(script, callback[, options]);
参数
参数 | 类型 | 说明 |
---|---|---|
script |
字符串 |
脚本的名称。支持的脚本包括 '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 跟踪代码管理器脚本。
|
callback |
函数 |
可通过脚本及其元数据调用的回调函数,在请求失败或超时的情况下,则为 undefined 和空元数据对象。
|
options |
对象 | 可选的请求选项。请参阅下文,了解受支持的选项。 |
选项
选项 | 类型 | 说明 |
---|---|---|
id |
字符串 |
适用于具有 gtag 衡量 ID 的 'GTAG' 和具有网站容器 ID 的 'GTM' (例如 GTM-XXXX)。
|
debug |
任意类型 | 如果值为 true,则请求并返回调试版衡量脚本。 |
timeout |
数值 |
请求超时(以毫秒为单位);系统会忽略非正值。如果请求超时,对于脚本值,将使用 undefined 调用回调函数,对于元数据对象,将使用 {} 调用回调函数。
|
系统会忽略无法识别的选项键。
相关权限
需要 send_http
权限。此权限必须配置为至少允许访问以下内容:
- 允许 Google 网域
getRemoteAddress
通过读取 Forwarded 和 X-Forwarded-For 等请求标头,返回发起请求的 IP 地址的字符串表示形式,例如 12.345.67.890
(对于 IPv4)或 2001:0db8:85a3:0:0:8a2e:0370:7334
(对于 IPv6)。注意:此 API 会尽最大努力查找发起请求的 IP 地址,但无法保证结果的准确性。
语法
getRemoteAddress();
相关权限
需要 read_request
权限。此权限必须配置为至少允许访问以下内容:
- 标头
Forwarded
和X-Forwarded-For
- 远程 IP 地址
getRequestBody
如果存在,则以字符串形式返回请求正文,否则返回 undefined
。
语法
getRequestBody();
相关权限
getRequestHeader
如果存在,则以字符串形式返回已命名的请求标头的值,否则返回 undefined
。如果该标头重复出现,则返回的值会使用 ', '
组合在一起。
示例
const getRequestHeader = require('getRequestHeader');
const host = getRequestHeader('host');
语法
getRequestHeader(headerName);
参数
参数 | 类型 | 说明 |
---|---|---|
headerName |
字符串 | 标头名称。此值不区分大小写。 |
相关权限
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();
相关权限
getRequestQueryParameter
以字符串形式返回已命名的查询字符串参数解码后的值;如果该参数不存在,则返回 undefined
。如果该参数在查询字符串中重复出现,则会返回查询字符串中出现的第一个值。
示例
const getRequestQueryParameter = require('getRequestQueryParameter');
const query = getRequestQueryParameter('query');
if (query) {
// Process query here.
}
语法
getRequestQueryParameter(name);
参数
参数 | 类型 | 说明 |
---|---|---|
name |
字符串 | 查询参数名称。 |
相关权限
getRequestQueryParameters
以对象形式返回传入 HTTP 请求的查询参数,该对象会将查询参数名称映射到对应的一个或多个值。参数名称和值已解码。
示例
const getRequestQueryParameters = require('getRequestQueryParameters');
const queryParameters = getRequestQueryParameters();
if (queryParameters['search']) {
// Handle the search query here.
const maxResults = queryParameters['max_results'];
}
语法
getRequestQueryParameters();
相关权限
getRequestQueryString
以字符串形式返回请求查询,不带前导问号;如果请求网址不包含查询字符串,则返回空字符串。
示例
const getRequestQueryString = require('getRequestQueryString');
const queryString = getRequestQueryString();
if (queryString !== '') {
// Handle the query string.
}
语法
getRequestQueryString();
相关权限
getTimestamp
已弃用。优先使用 getTimestampMillis。
返回一个表示当前时间的数字,该数字是指自 Unix 纪元起到当前时间经过了多少毫秒,与 Date.now()
返回的值相同。
语法
getTimestamp();
相关权限
无。
getTimestampMillis
返回一个表示当前时间的数字,该数字是指自 Unix 纪元起到当前时间经过了多少毫秒,与 Date.now()
返回的值相同。
语法
getTimestampMillis();
相关权限
无。
getType
返回一个字符串,该字符串描述了指定值的类型。
输入类型 | 返回值 |
---|---|
字符串 | 'string' |
数值 | 'number' |
布尔值 | 'boolean' |
null | '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 |
任意类型 | 输入值。 |
相关权限
无。
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 Console 的日志浏览器中查看。在日志浏览器中,运行查询 logName =~ "stdout"
以查看此 API 创建的日志条目。
示例
const logToConsole = require('logToConsole');
const that = 123;
const those = { ... };
logToConsole('that is: ', that, ' and those is: ', those);
语法
logToConsole(argument1[, argument2, ...]);
参数
该 API 会采用一个或多个参数,其中每个参数都会转换为字符串(如有必要),并记录到控制台中。
相关权限
makeInteger
将指定的值转换为数字(整数)。
语法
makeInteger(value);
参数
参数 | 类型 | 说明 |
---|---|---|
value |
任意类型 | 要转换的值。 |
相关权限
无。
makeNumber
将指定的值转换为数字。
语法
makeNumber(value);
参数
参数 | 类型 | 说明 |
---|---|---|
value |
任意类型 | 要转换的值。 |
相关权限
无。
makeString
以字符串的形式返回指定的值。
语法
makeString(value);
参数
参数 | 类型 | 说明 |
---|---|---|
value |
任意类型 | 要转换的值。 |
相关权限
无。
makeTableMap
将包含两列的简单表格对象转换为 Map
。它用于将包含两列的 SIMPLE_TABLE
模板字段转换为更易于管理的格式。
例如,此函数可将以下表格对象:
[
{'key': 'k1', 'value': 'v1'},
{'key': 'k2', 'value': 'v2'}
]
转换为以下映射关系:
{
'k1': 'v1',
'k2': 'v2'
}
返回一个对象:如果为此函数添加了键值对,则返回转换后的 Map
;否则,返回 null
。
语法
makeTableMap(tableObj, keyColumnName, valueColumnName);
参数
参数 | 类型 | 说明 |
---|---|---|
tableObj |
列表 |
要转换的表格对象。这是一个映射关系列表,其中每个 Map 表示表格中的一行。行对象中的每个属性名称都是列名称,而属性值则是该行中的列值。
|
keyColumnName |
字符串 |
列的名称,表示哪个列的值在转换后的 Map 中将成为键。
|
valueColumnName |
字符串 |
列的名称,表示哪个列的值在转换后的 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 |
字符串 | 要解析的完整网址。 |
相关权限
无。
returnResponse
使用可修改响应的 API 清空其他模板之前设置的响应,其中包括:setCookie、setPixelResponse、setResponseBody、setResponseHeader 和 setResponseStatus。默认为 HTTP 状态代码 200、空正文和无标头。
建议您通过客户端模板使用此 API。
语法
returnResponse();
示例
请参阅 runContainer
示例。
相关权限
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 |
函数 | 在代码开始触发前立即调用的回调函数。 |
相关权限
sendEventToGoogleAnalytics
将采用统一架构格式的单个事件发送到 Google Analytics(分析)。
示例
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, (response) => {
if (!response.success) {
setResponseStatus(500);
data.gtmOnFailure();
return;
}
if (response.location) {
setResponseHeader('location', response.location);
setResponseStatus(302);
} else {
setResponseStatus(200);
}
data.gtmOnSuccess();
});
语法
sendEventToGoogleAnalytics(event, callback);
参数
参数 | 类型 | 说明 |
---|---|---|
event |
对象 | 采用统一架构格式的事件。 |
callback |
函数 |
将在命中数据发送到 Google Analytics(分析)后调用的可选回调函数。系统将使用包含 success 和 location 字段的对象调用该函数。 如果响应代码为 200 或 302,则 success 字段设置为 true ,否则设置为 false 。如果响应中包含 location 标头,则 location 字段设置为标头值。
|
相关权限
需要 send_http
权限。此权限必须配置为至少允许访问以下内容:
- 允许 Google 网域
sendHttpGet
向指定网址发出 HTTP GET 请求,并在请求完成或超时后通过响应调用回调函数。
示例
const sendHttpGet = require('sendHttpGet');
const setResponseBody = require('setResponseBody');
const setResponseHeader = require('setResponseHeader');
const setResponseStatus = require('setResponseStatus');
// Sends a GET request and nominates response
// based on the response from the GET request.
sendHttpGet('https://example.com/collect', (statusCode, headers, body) => {
setResponseBody(body);
setResponseHeader('cache-control', headers['cache-control']);
setResponseStatus(statusCode);
}, {headers: {key: 'value'}, timeout: 500});
语法
sendHttpGet(url[, callback[, options]]);
参数
参数 | 类型 | 说明 |
---|---|---|
url |
字符串 | 请求网址。 |
callback |
函数 |
将在请求完成、出现错误或超时后调用的可选回调函数。 可使用响应状态代码、响应标头和响应正文(如果没有响应正文,则使用未定义的正文)调用该函数。 如果请求失败(例如网址无效、没有通向主机的路由、SSL 协商失败等),系统将使用响应状态代码“0”、无标头和未定义的正文来调用该回调函数。 如果已设置 'timeout' 选项且请求超时,系统将使用响应状态代码“-1”、无标头和未定义的正文来调用该回调函数。
|
options |
对象 | 可选的请求选项。支持的选项包括:标头和超时。系统会忽略未知的选项键(请参阅下文中的选项部分)。 |
- 标头:以对象形式表示的其他请求标头。
- 超时:表示请求取消之前的超时时间(以毫秒为单位)。
相关权限
sendHttpRequest
向指定网址发出 HTTP 请求,并在请求完成或超时后使用响应调用回调函数。
示例
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', (statusCode, headers, body) => {
setResponseStatus(statusCode);
setResponseBody(body);
setResponseHeader('cache-control', headers['cache-control']);
}, {headers: {key: 'value'}, method: 'POST', timeout: 500}, postBody);
语法
sendHttpRequest(url[, callback[, options[, body]]]);
参数
参数 | 类型 | 说明 |
---|---|---|
url |
字符串 | 请求网址。 |
callback |
函数 |
将在请求完成、出现错误或超时后调用的可选回调函数。 可使用响应状态代码、响应标头和响应正文(如果没有响应正文,则使用未定义的正文)调用该函数。 如果请求失败(例如网址无效、没有通向主机的路由、SSL 协商失败等),系统将使用响应状态代码“0”、无标头和未定义的正文来调用该回调函数。 如果已设置“超时”选项且请求超时,系统将使用响应状态代码“-1”、无标头和未定义的正文来调用该回调函数。 |
options |
对象 | 可选的请求选项。支持的选项包括:标头、方法和超时。系统会忽略未知的选项键(请参阅下文中的选项部分)。 |
body |
字符串 | 可选的请求正文。 |
- 标头:其他请求标头。
- 方法:请求方法,默认为“GET”。
- 超时:表示请求取消之前的超时时间(以毫秒为单位)。
相关权限
sendPixelFromBrowser
向浏览器发送一个命令,将提供的网址作为 <img>
代码加载。Google Analytics(分析):GA4 配置和 Google Analytics(分析):GA 事件网络代码支持此命令协议。您必须在配置代码中启用发送到服务器容器选项。请参阅相关说明了解详情。
如果收到的请求不支持命令协议,或响应已刷新,则此 API 会返回 false
。否则,此 API 会返回 true
。
示例:
const sendPixelFromBrowser = require('sendPixelFromBrowser');
sendPixelFromBrowser('https://example.com/?id=123');
语法
sendPixelFromBrowser(url)
参数
参数 | 类型 | 说明 |
---|---|---|
url |
字符串 | 要发送到浏览器的网址。 |
相关权限
setCookie
根据指定的选项设置或删除 Cookie。
要删除某个 Cookie,必须使用该 Cookie 创建时所用的同一路径和域名对其进行设置,并为其指定一个使用过去时间的 expires 值,例如 "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 |
字符串 | Cookie 名称。该名称不区分大小写。 |
value |
字符串 | Cookie 值。 |
options |
对象 | 可选的 Cookie 属性:domain、expires、fallbackDomain、httpOnly、max-age、path、secure 和 sameSite。(请参阅下文中的选项部分)。 |
noEncode |
布尔值 |
如果值为 true,则不会对 Cookie 值进行编码。默认值为 false 。
|
domain:用于接收 Cookie 的主机。如果设置为特殊值“auto”,则系统会使用以下策略自动计算主机:
Forwarded
标头的 eTLD+1(如果存在)。X-Forwarded-Host
标头的 eTLD+1(如果存在)。Host
标头的 eTLD+1。
expires:Cookie 的最长有效期。该值必须是采用 UTC 格式的日期字符串,例如“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'
。
相关权限
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 |
字符串 | 要设置为响应正文的值。 |
encoding |
字符串 |
响应正文的字符编码(默认为 'utf8' )。支持的值包括:'ascii' 、'utf8' 、'utf16le' 、'ucs2' 、'base64' 、'latin1' 、'binary' 和 'hex' 。
|
相关权限
需要 access_response
权限。此权限必须配置为至少允许访问以下内容:
body
setResponseHeader
在要返回的响应中设置标头。如果采用此名称(不区分大小写)的标头以前曾通过此 API 进行了设置,那么,后面的调用会覆盖或清除前面的调用方设置的值。
请注意,要将该响应发送回客户端,必须调用 returnResponse。
语法
setResponseHeader(name, value);
参数
参数 | 类型 | 说明 |
---|---|---|
name |
字符串 | 标头名称。HTTP 标头名称不区分大小写,因此标头名称将采用小写形式。 |
value |
字符串(未定义) | 标头值。如果为 null 或 undefined,系统会从要返回的响应中清除已命名的标头。 |
相关权限
需要 access_response
权限。此权限必须配置为至少允许访问以下内容:
headers
setResponseStatus
设置要返回的响应的 HTTP 状态代码。
请注意,要将该响应发送回客户端,必须调用 returnResponse。
语法
setResponseStatus(statusCode);
参数
参数 | 类型 | 说明 |
---|---|---|
statusCode |
数值 | 要返回的 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 |
字符串 | 要进行哈希处理的字符串。 |
onSuccess |
函数 |
通过计算得出的、采用 base64 编码的摘要进行调用,除非 options 对象指定其他输出编码。
|
options |
对象 |
用于指定输出编码的选项对象,此参数可选。如果已指定,则该对象应包含值为 base64 或 hex 其中之一的键 outputEncoding 。
|
相关权限
无。
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 |
字符串 | 要进行哈希处理的字符串。 |
options |
对象 |
用于指定输出编码的选项对象,此参数可选。如果已指定,则该对象应包含值为 base64 或 hex 其中之一的键 outputEncoding 。
|
相关权限
无。
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 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, (statusCode, headers, body) => {
if (status >= 200 && status < 300) {
setResponseBody(body);
templateDataStorage.setItemCopy(data.key, body);
data.gtmOnSuccess();
} else {
data.gtmOnFailure();
}
setResponseStatus(statusCode);
});
相关权限
toBase64
对字符串进行 base64 编码。
语法
toBase64(input);
参数
参数 | 类型 | 说明 |
---|---|---|
input |
字符串 | 要编码的字符串。 |
示例
const toBase64 = require('toBase64');
const base64Hello = toBase64('hello');
相关权限
无。
BigQuery
返回一个提供 BigQuery 函数的对象。
BigQuery.insert
函数允许将数据写入 BigQuery 表。
语法
BigQuery.insert(connectionInfo, rows, options, onSuccess, onFailure);
参数 | 类型 | 说明 |
---|---|---|
connectionInfo |
对象 |
定义连接到 BigQuery 表所需的信息。有一个可选参数和两个必需参数:
|
rows |
数组 | 要插入到表中的行。 |
options |
对象 | 可选的请求选项。支持的选项包括:ignoreUnknownValues 和 skipInvalidRows。系统会忽略未知的选项键。(请参阅下文中的选项部分。) |
onSuccess |
函数 | 将在成功插入后调用的可选回调函数。系统在调用此回调函数时不使用任何参数。 |
onFailure |
函数 | 将在出现错误后调用的可选回调函数。如果出现错误,系统会使用包含错误原因的对象列表调用此回调函数,可能的话,还会使用行对象。出现错误的原因可能是请求的某一部分成功完成,但其他部分未能完成。在这种情况下,系统会使用每行的错误列表和行对象调用 onFailure ,以帮助区分插入了哪些行(请参阅下文的错误示例部分)。如需了解详情,请参阅 BigQuery 有关错误消息的文档。 |
参数 | 类型 | 说明 |
---|---|---|
ignoreUnknownValues |
布尔值 | 如果设置为 true ,则会接受包含与架构不匹配的值的行。未知值会被忽略。默认值为 false 。 |
skipInvalidRows |
布尔值 | 如果设置为 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, data.gtmOnSuccess, data.gtmOnFailure);
相关权限
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 发送该类型的消息(通常是通过代码)时,回调函数将同步运行。通过以下两个参数运行该回调函数:
messageType:string
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 |
字符串 | 要监听的消息类型。如果值不是字符串,系统会将其强制转换为字符串。 |
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
向已注册监听器发送指定类型的消息。此 API 可用于将消息从代码发送回运行容器的客户端。
语法
const sendMessage = require('sendMessage');
sendMessage('send_pixel', {url: 'https://analytics.example.com/collect'});
参数
参数 | 类型 | 说明 |
---|---|---|
messageType |
字符串 | 要发送的消息类型。如果值不是字符串,系统会将其强制转换为字符串。 |
message |
对象 | 要发送的消息。如果消息不是对象,该 API 将不执行任何操作。 |
相关权限
需要 use_message
权限。此权限必须配置为至少允许以下内容:
- 一种
Usage
为listen_and_send
或send
的消息类型。
测试 API
这些 API 采用在沙盒中运行的 JavaScript 测试,在 Google 跟踪代码管理器中为自定义模板构建测试。这些测试 API 不需要使用 require()
语句。[详细了解自定义模板测试]。
assertApi
返回一个匹配函数对象,该对象可用于顺畅地就指定的 API 进行断言。
语法
assertApi(apiName)
参数
参数 | 类型 | 说明 |
---|---|---|
apiName |
字符串 | 要检查的 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 |
任意类型 | 完成顺畅检查所用的值。 |
opt_message |
字符串 | 断言失败时输出的消息(可选)。 |
匹配函数
匹配函数 | 说明 |
---|---|
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 |
字符串 | 错误消息文本(可选)。 |
示例
fail('This test has failed.');
mock
mock
API 用于覆盖在沙盒中运行的 API 的行为。mock API 在模板代码中可以安全使用,但在非测试模式下无法运行。在每个测试运行前,模拟都会被重置。
语法
mock(apiName, returnValue);
参数
参数 | 类型 | 说明 |
---|---|---|
apiName |
字符串 | 要模拟的 API 的名称;与传递给 require() 的字符串相同 |
returnValue |
任意类型 | 要为此 API 返回的值或者代替此 API 被调用的函数。如果 returnValue 是函数,则调用该函数,而不是在沙盒中运行的 API;如果 returnValue 是除函数之外的任何其他值,则返回该值,而不是在沙盒中运行的 API。 |
示例
mock('encodeUri', "https://endpoint.example.com/?account=12345");
mock('sendPixel', function(url, onSuccess, onFailure) {
onSuccess();
});
runCode
使用指定的输入数据对象在当前测试环境中运行模板代码,即代码标签页中的内容。
语法
runCode(data)
参数
参数 | 类型 | 说明 |
---|---|---|
data |
对象 | 要在测试中使用的数据对象。 |
返回值
对于变量模板,返回相应变量的值;对于所有其他模板类型,返回 undefined
。
示例
runCode({field1: 123, field2: 'value'});