Convert Google Analytics cookies to Local/Session Storage

佐手、 提交于 2019-11-27 18:12:24
Elmer

Use this:

(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','//www.google-analytics.com/analytics.js','ga');

if(window.localStorage) {
    ga('create', 'UA-98765432-1', 'www.example.com', {
      'storage': 'none'
      , 'clientId': window.localStorage.getItem('ga_clientId')
    });
    ga(function(tracker) {
      window.localStorage.setItem('ga_clientId', tracker.get('clientId'));
    });
}
else {
    ga('create', 'UA-98765432-1', 'www.example.com');
}
ga('send', 'pageview');

First, I check if localStorage is supported. If it is supported then the 'storage': 'none' option will disable cookies. Now we can set the clientId from localStorage. If it is empty, Google Analytics will generate a new one for us. We save the new (or existing) clientid in localStorage after the tracker loads.

If localStorage is not supported, I just use the regular analytics method. After the initialization I send a pageView via ga('send', 'pageView').

Also, check out this plunk: http://plnkr.co/MwH6xwGK00u3CFOTzepK

rjmunro

Some experimentation in chrome shows that it may be possible to use getters and setters to patch document.cookie for this, something like:

document.__defineGetter__('cookie', function () {
    // Replace this with code to read from localstorage
    return "hello";
});
document.__defineSetter__('cookie', function (value) {
    // Replace this with code to save to localstorage
    console.log(value);
});

ga.js (or any other javascript) could run and access cookies as normal, they just would never get passed to the server.

Obviously this will only work in some browsers. Browsers in which it doesn't work will have to fall back to normal cookies.

There's some related ideas in this question: Is it possible to mock document.cookie in JavaScript?

Yes it can be done. You only have to request the __utm.gif with the parameters. The rest of the data is just used for keeping track of the source, session start time and/or previous visits.

You can easily transfer the cookies both ways, so your first approach should work fine.

If your second approach works... not sure. I don't know the ga.js code good enough to estimate wheter that would or would not be easily possible.

There is also a third option, run your own version of ga.js. You are not required to use the Google version.

Can it be done as described above? Yes

Why hasn't it been done?

  1. the cookies are small, there isn't that much benefit if you use cookieless domains for all your static content
  2. it's less convenient since a lot of browsers don't support it yet
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!