Zaraz Worker Variables 是一种功能强大的变量类型,你可以对其进行配置,然后在 actions 和 triggers 中使用。与字符串变量和掩码变量不同,Worker Variables 是动态的。这意味着你可以使用 Cloudflare Worker 来确定变量的值,从而将其用于无数用途。例如:
- 计算购物车中所有产品总价的 Worker Variable
- 获取 cookie、向你的后端发出请求并返回 User ID 的 Worker Variable
- 在将值发送给第三方供应商之前先进行哈希处理的 Worker Variable
要使用 Worker Variable,你首先需要创建一个新的 Cloudflare Worker。你可以通过 Cloudflare 仪表板或使用 Wrangler 完成此操作。
要在 Cloudflare 仪表板中创建新的 Worker:
-
在 Cloudflare 仪表板中,前往 **Workers and Pages(Workers 和 Pages)**页面。
Go to Workers & Pages ↗ -
选择 Create application(创建应用程序)。
-
为你的 Worker 命名,然后选择 Deploy(部署)。
-
选择 Edit code(编辑代码)。
你现在已创建了一个响应 "Hello world." 的基本 Worker。如果你将此 Worker 用作 Variable,你的 Variable 将始终输出 "Hello world."。来自 Worker 的响应正文将成为 Worker Variable 的值。为了使此 Worker 真正有用,你通常会希望使用来自 Zaraz 的信息,即 Zaraz Context。
Zaraz 会将 Zaraz Context 对象作为 JSON 载荷,通过 POST 请求转发给你的 Worker。你可以像这样访问任意属性:
const { system, client } = await request.json()
/* System parameters */
system.page.url.href // URL of the current page
system.page.query.gclid // Value of the gclid query parameter
system.device.resolution // Device screen resolution
system.device.language // Browser preferred language
/* Zaraz Track values */
client.value // value from `zaraz.track("foo", {value: "bar"})`
client.products[0].name // name of the first product in an ecommerce call继续阅读以了解不同用例的更完整示例,或参阅 Zaraz Context。
Worker 发布后,配置 Worker Variable 非常简单。
-
在 Cloudflare 仪表板中,前往 **Tag Setup(标签设置)**页面。
Go to Tag setup ↗ -
选择要配置变量的域名。
-
选择 **Variables(变量)**选项卡。
-
选择 Create variable(创建变量)。
-
为变量命名,将 **Variable type(变量类型)**选择为 Worker,然后选择你新创建的 Worker。
-
保存变量。
现在 Worker Variable 已配置完成,你可以在 actions 和 triggers 中使用它。
要使用你的 Worker Variable:
-
在 Cloudflare 仪表板中,前往 **Tag Setup(标签设置)**页面。
Go to Tag setup ↗ -
选择要配置变量的域名。
-
在已配置的工具旁选择 Edit(编辑)。
-
选择一个 action,或添加一个新 action。
-
选择文本字段右侧的加号。
-
从列表中选择你的 Worker Variable。
假设我们像这样发送购物车中的产品列表:
zaraz.ecommerce("Cart Viewed", {
products: [
{ name: "shirt", price: "50" },
{ name: "jacket", price: "20" },
{ name: "hat", price: "30" },
],
});可以像这样计算总和:
export default {
async fetch(request, env) {
// Parse the Zaraz Context object
const { system, client } = await request.json();
// Get an array of all prices
const productsPrices = client.products.map((p) => p.price);
// Calculate the sum
const sum = productsPrices.reduce((partialSum, a) => partialSum + a, 0);
return new Response(sum);
},
};Zaraz 会自动在 system.cookies 对象下公开所有 cookie,因此它们始终可用。访问 cookie 并用它查询后端可能如下所示:
export default {
async fetch(request, env) {
// Parse the Zaraz Context object
const { system, client } = await request.json();
// Get the value of the cookie "login-cookie"
const cookieValue = system.cookies["login-cookie"];
const userId = await fetch("https://example.com/api/getUserIdFromCookie", {
method: POST,
body: cookieValue,
});
return new Response(userId);
},
};假设你正在发送一个希望进行哈希处理的值,例如电子邮件地址:
zaraz.track("user_logged_in", { email: "user@example.com" });你可以像这样访问该属性并对其进行哈希处理:
async function digestMessage(message) {
const msgUint8 = new TextEncoder().encode(message); // encode as (utf-8) Uint8Array
const hashBuffer = await crypto.subtle.digest("SHA-256", msgUint8); // hash the message
const hashArray = Array.from(new Uint8Array(hashBuffer)); // convert buffer to byte array
const hashHex = hashArray
.map((b) => b.toString(16).padStart(2, "0"))
.join(""); // convert bytes to hex string
return hashHex;
}
export default {
async fetch(request, env) {
// Parse the Zaraz Context object
const { system, client } = await request.json();
const { email } = client;
return new Response(await digestMessage(email));
},
};