如何通过Google Apps Script检测网站重复GA4页面视图代码?
解决Google Apps Script检测网站重复GA4页面视图ID的问题
核心限制说明
你之前在Chrome控制台用performance.getEntriesByType的方法无法直接迁移到Google Apps Script(GAS)——因为GAS运行在服务器端环境,没有浏览器的performance对象,也无法模拟浏览器加载页面并执行前端JS、监听网络请求。必须换两种思路实现:静态解析页面GA4代码,或结合浏览器模拟服务。
方案1:用Cheerio静态抓取页面GA4配置(纯GAS实现)
如果客户网站的GA4是通过静态脚本嵌入(比如直接在HTML里写gtag('config', 'G-XXXX')),可以用GAS的UrlFetchApp获取页面HTML,再用Cheerio库解析提取GA4 ID,最后统计重复情况。
步骤:
在GAS编辑器中添加Cheerio库:
- 点击「资源」→「库」,输入库ID:
1ReeQ6WO8kKNxoaA_O0XEQ589cIrRvEBA9qcWpNqdOP17i47u6N9M5Xh0,选择最新版本,保存。
- 点击「资源」→「库」,输入库ID:
实现核心检测代码:
function checkGA4Duplicates(url) { // 补全URL协议(避免无http/https的情况) if (!url.match(/^https?:\/\//)) { url = `https://${url}`; } try { // 获取目标网站HTML内容 const response = UrlFetchApp.fetch(url, { muteHttpExceptions: true }); const html = response.getContentText(); // 用Cheerio解析HTML const $ = Cheerio.load(html); const ga4Ids = []; // 遍历所有script标签,提取GA4 ID $('script').each((_, elem) => { const scriptContent = $(elem).html(); if (scriptContent?.includes("gtag('config'")) { // 匹配G-开头的GA4 ID格式 const matches = scriptContent.match(/G-[A-Z0-9]{10,}/g); if (matches) ga4Ids.push(...matches); } }); // 统计每个ID的出现次数 const idCounter = {}; ga4Ids.forEach(id => { idCounter[id] = (idCounter[id] || 0) + 1; }); // 生成结果文本 let result = `${url} `; const duplicateEntries = Object.entries(idCounter).filter(([_, count]) => count > 1); if (duplicateEntries.length > 0) { result += duplicateEntries.map(([id, count]) => `has ${count} instances of GA4 ID - ${id}` ).join(' & '); } else { result += 'has no duplicate GA4 IDs'; } return result; } catch (err) { return `${url} - Error: ${err.message}`; } }
局限:
- 只能检测静态嵌入的GA4配置,无法捕获通过Tag Manager、异步JS加载的动态GA4代码(因为Cheerio不执行前端JS)。
方案2:模拟浏览器捕获动态GA4请求(覆盖所有场景)
要完全复刻Chrome控制台的逻辑(捕获en=page_view的网络请求),必须借助无头浏览器环境执行页面JS并监听网络请求。你可以:
实现思路:
- 用Node.js + Puppeteer写一个简单的服务:加载目标页面,监听所有网络请求,筛选出包含
en=page_view的请求,提取tid参数(GA4 ID),统计重复情况。 - 将这个服务部署为云函数(比如Google Cloud Functions、AWS Lambda),然后在GAS中通过
UrlFetchApp调用该云函数的API,获取检测结果。
Puppeteer核心代码示例(Node.js):
const puppeteer = require('puppeteer'); async function checkGA4PageViews(url) { const browser = await puppeteer.launch({ headless: 'new' }); const page = await browser.newPage(); const ga4Ids = []; // 监听网络请求 await page.setRequestInterception(true); page.on('request', req => { const url = req.url(); if (url.includes('en=page_view') && url.includes('tid=')) { // 提取tid参数 const tid = new URL(url).searchParams.get('tid'); if (tid) ga4Ids.push(tid); } req.continue(); }); await page.goto(url, { waitUntil: 'networkidle2' }); await browser.close(); // 统计重复ID const idCounter = {}; ga4Ids.forEach(id => { idCounter[id] = (idCounter[id] || 0) + 1; }); const duplicates = Object.entries(idCounter).filter(([_, count]) => count > 1); if (duplicates.length > 0) { return `${url} ${duplicates.map(([id, count]) => `has ${count} GA4 page_view requests with ID - ${id}` ).join(' & ')}`; } else { return `${url} has no duplicate GA4 page_view requests`; } }
第三方工具推荐
如果不想自己开发,可以使用专注于网站标签审计的工具:
- 这类工具会模拟浏览器加载页面,捕获所有标签触发的网络请求,能准确识别重复的GA4页面视图调用,还能检测其他标签问题(比如GTM配置错误、UA代码残留等)。
- 部分工具支持批量检测多个网站,直接导出检测结果到表格,适配你的业务场景。
内容的提问来源于stack exchange,提问作者Arif Ahmed
相关产品推荐
相关产品推荐

