You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何跨页面启动并保留计时器,通过Google Analytics记录操作时长?

跨页面任务时长统计并上报Google Analytics实现方案

核心思路

要实现从page-a.php点击按钮到page-2.php提交任务的时长统计,关键是在page-a启动计时并把起始时间跨页面传递给page-2,待page-2提交时计算总耗时,再通过你提供的GA代码上报。

具体实现步骤

1. 在page-a.php中启动计时并存储起始时间

给打开page-2的按钮绑定点击事件,记录精确起始时间并存在sessionStorage中(同域名下跨页面共享,关闭页面自动清除,适合临时数据):

// page-a.php 按钮点击逻辑
document.getElementById('open-page2-btn').addEventListener('click', function() {
    // 用performance.now()获取高精度起始时间(页面加载后的毫秒数)
    const startTime = performance.now();
    // 存入sessionStorage,转成字符串存储
    sessionStorage.setItem('taskStartTime', startTime.toString());
    // 打开page-2.php,根据需求用window.open(新窗口)或window.location.href(跳转)
    window.open('page-2.php', '_blank');
});

2. 在page-2.php中计算时长并上报GA

给提交按钮绑定事件,读取起始时间计算总耗时,再调用GA接口上报:

// page-2.php 提交按钮逻辑
document.getElementById('submit-btn').addEventListener('click', function() {
    // 从sessionStorage读取起始时间并转成数字
    const startTime = parseFloat(sessionStorage.getItem('taskStartTime'));
    
    // 校验:确保performance API可用且起始时间有效
    if (window.performance && !isNaN(startTime)) {
        // 计算任务总耗时(当前时间 - 起始时间),取整符合GA要求
        const taskDuration = Math.round(performance.now() - startTime);
        
        // 上报到Google Analytics,可自定义事件名称和分类
        gtag('event', 'timing_complete', {
            'name': 'task_completion_duration', // 自定义事件名称,比如“任务完成时长”
            'value': taskDuration,
            'event_category': 'User Task Performance' // 自定义分类,方便GA后台筛选
        });
        
        // 上报后清除存储,避免重复统计
        sessionStorage.removeItem('taskStartTime');
    }
});

替代方案(不同域名场景)

如果page-a和page-2不在同域名下,sessionStorage无法共享,可通过URL参数传递起始时间:

  • page-a.php中拼URL:
const startTime = performance.now();
window.open(`page-2.php?startTime=${startTime}`, '_blank');
  • page-2.php中读取URL参数:
// 解析URL参数
const urlParams = new URLSearchParams(window.location.search);
const startTime = parseFloat(urlParams.get('startTime'));
// 后续计算和上报逻辑同上

注意事项

  • 确保浏览器允许弹窗(如果用window.open),否则会导致跳转失败。
  • 若用户在page-2刷新页面,sessionStorage中的起始时间会保留,但URL参数方案会丢失,可根据需求选择存储方式。
  • performance.now()比Date.now()精度更高(微秒级),适合计时场景;如果需要兼容极旧浏览器,可替换为Date.now()。

内容的提问来源于stack exchange,提问作者santa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 03:30:52