JSFiddle - React, Tailwind, and code Playground

by davidmurdoch

HTML

<!-- me: twitter.com/vervestudiosco -->

<h1>Using localStorage instead of cookies for Google Analytics</h1>

<p>Beware: this is not even a proof of concept - just something I have been thinking about for a while. I'm really just tinkering with the idea. <em>I don't even know if this works (yet).</em>
<br /><br /> The original idea: <a href="http://stackoverflow.com/questions/4502128/convert-google-analytics-cookies-to-local-session-storage">http://stackoverflow.com/questions/4502128/convert-google-analytics-cookies-to-local-session-storage</a>
<p>
    <strong>The code really sucks. Get over it.</strong>
<p>
    <h2>When this page loads in a browser that supports localStorage the following events occur:</h2>
    <ol>
        <li>Any cookies that were previously cloned into localStorage are reinserted into document.cookie
        <li>We load ga.js (Google Analytics) using our modified version of Mathias Bynens script.
        <li>When Analytics (on)loads/runs we retrieve the cookie values, insert them into localStorage, then delete those cookies.    
    </ol>
<p>
    <h2>Why the heck would you want to do that?</h2>
    <ul>
        <li>Without it every Google Analytics cookie is sent needlessly to your server (in some [probably most] cases this happens for all static content, such as images, js, and css, too!).
        <li>If we delete the cookies and only add them in when ga.js actually needs them we'll end up saving some bytes!
        <li>Why not?
            </ul>
<p>
    <h2>Issues</h2>
    <ul>
        <li>The current setup does not respect cookie expiration at all.
        <li>I'm not sure if it even works. Its just an idea.
        <li>The cookie object being using adds more weight to the page then the cookies do. This could probably be fixed pretty easily though.
            </ul>
        
<p>      
    If you are too lazy to view-source here is the good stuff (<code>cookies</code> is an object with <code>set</code>, <code>get</code>, and...

CSS

and

JavaScript

var _gaq=[['_setAccount','UA-2989939-8'],['_trackPageview'],['_trackPageLoadTime']];
(function(d,t){
    // this cookies object probably sucks. it is copy/pasted from a Google search and should probably be redone.
    var cookies={set:function(d,b,a,e,f,g){var c=new Date;c.setTime(c.getTime());a&&(a*=864E5);c=new Date(c.getTime()+a);document.cookie=d+"="+escape(b)+(a?";expires="+c.toGMTString():"")+(e?";path="+e:"")+(f?";domain="+f:"")+(g?";secure":"")},get:function(d){var b=document.cookie.split(";"),a="",e="",f="";for(i=0;i<b.length;i++)if(a=b[i].split("="),e=a[0].replace(/^\s+|\s+$/g,""),e==d)return a.length>1&&(f=unescape(a[1].replace(/^\s+|\s+$/g,""))),f;return null},del:function(d,b,a){try{if(function(a){var b=
document.cookie.split(";"),c="",d="",e="";for(i=0;i<b.length;i++)if(c=b[i].split("="),d=c[0].replace(/^\s+|\s+$/g,""),d==a)return c.length>1&&(e=unescape(c[1].replace(/^\s+|\s+$/g,""))),e;return null}(d))b=b||document.domain,document.cookie=d+"=; expires="+new Date+"; domain="+b+"; path="+(a||"/")}catch(e){}}};

    var g=d.createElement(t),
        s=d.getElementsByTagName(t)[0];

    if ( window.localStorage ) {
        var letters = "abcz".split(""),
            d = "." + location.host,
            i, name, value, undefined;
        // put cookie values into localStorage
        for ( i in letters ) {
            name = letters[i] = "__utm" + letters[i];
            if ( ( value=localStorage.getItem( name ) ) !== undefined ) {
                cookies.set( name, value, 365, d, "/" );
            }
        }
        // after ga.js runs add its cookies to localStorage then delete them
        g.onload = function() {
            for ( i in letters ) {
                name = letters[i];
                localStorage.setItem( name, cookies.get( name ) );
                cookies.del( name, d, "/" );
            }
        };
    }
    
    g.async=1;
    g.src=("https:"==location.protocol?"//ssl":"//www")+".google-analytics.com/ga.js";
   ...