如何在Google Tag Manager中设置JavaScript变量捕获未知数量电商商品参数
GTM中提取电商商品价格数组返回undefined的解决方法
问题描述
在Google Tag Manager(GTM)中配置Data Layer变量捕获电商数据时,单个商品的item_id、item_name、price、quantity字段可正常捕获,但处理未知数量的多商品时,提取价格数组的自定义JavaScript变量始终返回undefined。已确认ecommerce.items变量能正常返回完整的商品数组,但自定义JS变量无法正确提取价格数组。
触发的Data Layer事件
dataLayer.push({ event: "AddToCart", ecommerce: { currency: "USD", items: [ { item_id: "CTFBK", item_name: "Black Color Tissue Paper, 20x30\", Bulk 480 Sheet Flat Pack", price: 35.75, quantity: 1 }, { item_id: "18WK", item_name: "White Kraft Recycled Jewelry Boxes, 3.5x3.5x1\", 100 Pack, Fiber Fill", price: 49.2, quantity: 1 }, { item_id: "RBLBC", item_name: "Romantic Blooms Paper Gift Bag, Cub 8x4.75x10\", 250 Pack", price: 125, quantity: 3 } ] }, gtm.uniqueEventId: 25 })
ecommerce.items变量返回结果
[ { item_id: "CTFBK", item_name: "Black Color Tissue Paper, 20x30\", Bulk 480 Sheet Flat Pack", price: 35.75, quantity: 1 }, { item_id: "18WK", item_name: "White Kraft Recycled Jewelry Boxes, 3.5x3.5x1\", 100 Pack, Fiber Fill", price: 49.2, quantity: 1 }, { item_id: "RBLBC", item_name: "Romantic Blooms Paper Gift Bag, Cub 8x4.75x10\", 250 Pack", price: 125, quantity: 3 } ]
原自定义JavaScript变量代码
function() { var itemPrices = []; var items = {{ecommerce.items}}; if (items && items.length > 0) { for (var i = 0; i < items.length; i++) { if (items[i].price) { itemPrices.push(items[i].price); } } } return itemPrices; }
问题原因及修复方案
问题核心
原代码中存在HTML实体转义字符(&&、>、<),GTM的自定义JavaScript变量无法识别这些转义字符,会直接判定为语法错误,最终返回undefined。
修复后的代码
将转义字符替换为原生JavaScript运算符即可:
function() { var itemPrices = []; var items = {{ecommerce.items}}; if (items && items.length > 0) { for (var i = 0; i < items.length; i++) { if (items[i].price) { itemPrices.push(items[i].price); } } } return itemPrices; }
可选优化方案
可以用更简洁的数组方法实现相同逻辑,代码更易读:
function() { var items = {{ecommerce.items}}; return items && items.length > 0 ? items.filter(item => item.price).map(item => item.price) : []; }
验证步骤
- 替换自定义JavaScript变量的代码后,保存并发布GTM测试版本
- 进入GTM预览模式,触发
AddToCart事件 - 查看该自定义变量的返回值,应得到价格数组
[35.75, 49.2, 125]
内容的提问来源于stack exchange,提问作者Dizy
相关产品推荐
相关产品推荐

