如何检查是否设置了谷歌分析自定义变量(会话范围)



我正在尝试使用自定义变量跟踪会话范围内的用户类型。在每次加载页面时,我都想检查GA变量是否存在,如果不存在,则将其设置为基于cookie的3个值之一(访问者、注册者、高级用户)。

TrackUser: function () {
var index = 5; //slot 5
var scope = 2; //set scope to session level
var key = "UserType";
var value;
if (_gaq != undefined) {
_gaq.push(function () { //this is async
var pageTracker = _gat._getTrackerByName();    //Gets the default tracker.
var vis = pageTracker._getVisitorCustomVar(5); //this should return the 'usertype' if its been set
//if no GA variable exists then lets set it
if (vis == undefined) {    // !? THIS IS ALWAYS 'undefined' ?!
value = getUserType(); //get the users type
//send custom var to GA
_gaq.push(['_setCustomVar',
index,   // This custom var is set to slot #1.  Required parameter.
key,     // The name acts as a kind of category for the user activity.  Required parameter.
value,   // This value of the custom variable.  Required parameter.
scope    // Sets the scope to session-level.  Optional parameter.
]);
}
});
}
}

此函数是在跟踪事件推送"_trackEvent"之前调用的,因此它可能在调用"_track event"之前未完成。即便如此,它不会在下一页加载时发送吗?

还是我误解了GA如何使用自定义变量的cookie?

BTW:如果有一种更简单的方法来获得自定义变量(也许不必向谷歌发送请求),那将是理想的。

更新

在阅读更多文档后,我意识到"_getVisitorCustomVar"仅在自定义变量设置为"访问者范围"时才返回(3)。谷歌显然在服务器上跟踪"会话范围"(2)变量,并且不设置客户端cookie。在我找到一个更优雅的解决方案之前,我只是设置一个自己的会话cookie,以检查我是否已向GA发送了有关用户类型的信息。

只能从Google API调用_getVisitorCustomVar获取"访问者范围"值

var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'xxxxxxxxxxxxxxxx']);
_gaq.push(function() {
var pageTracker = _gat._getTrackerByName();
var userTypeVar = pageTracker._getVisitorCustomVar(1);
if ( userTypeVar == 'Guest' ) {
}
});
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

最新更新