使用 Google Analytics 在单页网站上跟踪用户

Tracking user on single page website with Google Analytics

最近我遇到了使用 Google Analytics 在 "single page website" 上跟踪用户的问题。我想分享我的解决方案。请看下面的答案。

最近我遇到了使用 Google Analytics 在 "single page website" 上跟踪用户的问题。我想分享我的解决方案。

----- 页面布局-----

1a. Header with logo and menu (links scroll page down to selected chapter)
2a. Section with big paralax bakground
2b. Chapter header <section><h2>Title 1</h2></section>
2c. Chapter's content <div>content</div>
3a. Section with big paralax bakground
3b. Chapter header <section><h2>Title 2</h2></section>
3c. Chapter's content <div>content</div>
...
Na. Section with big paralax bakground
Nb. Chapter header <section><h2>Title N</h2></section>
Nc. Chapter's content <div>content</div>

-----要求-----

  1. 算法必须检测页面何时向下滚动,以便用户可以看到所选章节。
  2. 算法必须检测到用户实际上花了一些时间来熟悉章节的内容。必须将此事实报告给 Google Analytics。
  3. 当用户只是滚动浏览章节时,算法无法报告用户阅读了该章节。

----算法-----

  1. 等待页面加载
  2. 创建章节列表及其相对于网站顶部边框的位置。
  3. 当用户看到所需的章节时,必须在一定时间后重新检查此条件,以证明用户确实花了一些时间阅读内容。
  4. 如果满足上述条件,请将此事实报告给 Google Analytics。

----示例代码-----

<script type="text/javascript">

var scrollstat = []

// Preparing array of chapters and positions
$(document).ready(function() {
    $("section").each(function() {
        var ts = {};
        ts["offset"] = $(this).offset();
        str = $("h2", this).html();
        ts["name"] = "SECTION-"+str.replace(" ","-")+"/";
        ts["checked"] = false;
        ts["timer"] = false;
        scrollstat.push(ts);
     });
});

//Checking that user is still on the same chapter
function doublecheck(ii) {
    scrollpos = $(window).scrollTop();
    max = scrollpos + 300;
    min = scrollpos;
    if (scrollstat[ii].checked == false && scrollstat[ii].offset.top > min
    && scrollstat[ii].offset.top < max) {
        _gaq.push(['_trackPageview', (location.pathname + location.search
        + scrollstat[ii].name)]);
        scrollstat[ii].checked = true;
    }
    console.log(scrollstat[ii].offset.top+','+min+','+max);
    scrollstat[ii].timer = false;
}


//Separate function for setting timer to count 3s
//If user don't scroll to other chapter within this time
//event is reported to GA

function settimer(ii) {
    scrollstat[ii].timer = true; 
    setTimeout(function() {doublecheck(ii);},3000);  
}

//Handling scrolling event
$(window).scroll(function() {
    scrollpos = $(window).scrollTop();
    max = scrollpos + 300;
    min = scrollpos;
    for (index = 0; index < scrollstat.length; ++index) {
        if (scrollstat[index].checked == false &&
        scrollstat[index].timer == false &&
        scrollstat[index].offset.top > min &&
        scrollstat[index].offset.top < max) {
              settimer(index);
        }
    }
});

</script>

MAX 和 MIN 变量是通过实验估计的。就我而言,我假设章节标题必须滚动到屏幕顶部。

作为上述脚本的结果,每个章节都作为单独的页面访问报告给 GA,地址如下:“/SECTION-chapter-title/”