将Google Analytics存储空间从Cookie迁移到本地存储

时间:2018-05-08 20:59:47

标签: google-analytics

在我们了解Google Analytics(analytics.js)的不同存储选项之前,我们启动了我们的网站并使用默认的基于Cookie的跟踪。我们现在想要切换到使用localStorage存储客户端ID,这样我们就不必为每个请求将cookie发送到服务器。

是否可以迁移拥有Cookie设置的用户,以便不是每个会话都会显示为新的全新用户?

1 个答案:

答案 0 :(得分:0)

这当然是可能的,诀窍是让Google Analytics脚本在您无法找到存储在本地存储中的ID时从Cookie中提取客户端ID。

/* Google Analytics initialization code */
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga')

/* Fallback to cookies if the browser doesn't support localStorage */
if (!window.localStorage) {
  ga('create', 'UA-XXXXX-Y', 'auto')
}

/* If we are already using localStorage, continue with that */
else if (localStorage.getItem('gaClientId')) {
  ga('create', 'UA-XXXXX-Y', { storage: 'none', clientId: localStorage.getItem('gaClientId') })
}

/* Migrate users from cookies to localStorage */
else if (document.cookies.indexOf('_ga') !== -1) {
  ga('create', 'UA-XXXXX-Y', { cookieExpires: 1 })
  ga(function (tracker) { localStorage.setItem('gaClientId', tracker.get('clientId')) })
}

/* Setup a fresh user */
else {
  ga('create', 'UA-XXXXX-Y', { storage: 'none' })
  ga(function (tracker) { localStorage.setItem('gaClientId', tracker.get('clientId')) })
}

ga('send', 'pageview')

在上一次cookie超时之后(如果未指定,则默认为2年),删除cookie-migration部分应该是安全的。然后该脚本将如下所示:

/* Google Analytics initialization code */
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga')

/* Fallback to cookies if the browser doesn't support localStorage */
if (!window.localStorage) {
  ga('create', 'UA-XXXXX-Y', 'auto')
}

/* Store Google Analytics client ID in localStorage */
else {
  ga('create', 'UA-XXXXX-Y', { storage: 'none', clientId: localStorage.getItem('gaClientId') })
  ga(function (tracker) { localStorage.setItem('gaClientId', tracker.get('clientId')) })
}

ga('send', 'pageview')