Tracking offline event with Google Analytics

pooya picture pooya · Nov 13, 2011 · Viewed 7.8k times · Source

I tried to track user activity in my site such as click or mouse over and different kind of events.... Is there any solution to track events even when users are working offline... Can I store them in something like cookie and send them to the server when find active internet connection?

Is that possible?

Thank you

Answer

Yahel picture Yahel · Nov 13, 2011

Depends on what browser types you're targeting. Are these for HTML5 offline webapps?

If they support ononline and onoffline events, you can implement this yourself fairly trivially.

Some potentially workable code, using offline events, native JSON and HTML5 Local Storage:

if(!localStorage.getItem("offlineGA")){
  localStorage.setItem("offlineGA","[]");
}
var _ogaq = {
push : function(arr){
    if(navigator.onLine || !("onLine" in navigator)){ // if online or if browser doesn't support onLine/offLine detection.
        _gaq.push(arr);
    }
    else{
     var stored = JSON.parse(localStorage.getItem("offlineGA"));
     stored.push(arr);
     localStorage.setItem("offlineGA", JSON.stringify(stored));
    }
}
};

$(window).bind("online", function(){ // if you don't have jQuery, you can do window.ononline instead
   _gaq.push( JSON.parse(localStorage.getItem("offlineGA")) );
   localStorage.setItem("offlineGA","[]"); //empty it
});

Then you would just use _ogaq as a wrapper for _gaq.

ie:

_ogaq.push(["_trackEvent","Category", "Action"]);