New day and another not publicly published functionality (not that I was aware of) has been added by Google to Universal Analytics JavaScript API.
Till now, for example if we wanted to track our outgoing links or our PDF downloads using an event or a virtual pageview to be sure that the info was really sent to Google Analytics we needed to either write some javascript to delay the user redirection to the destination page or using the hitCallback functionality that was added to universal.js some months ago.
This approach has a problem by itself, it will delay our user’s navigation, and if for some reason our delay function or hitCallback code was failing it will prevent our users to navigate to clicked link ( that’s not good, is it ? )
So it seems that since lastest Google Chrome release ( v37 ) it’s supporting the navigator.sendBeacon()
method . This method can be used to asynchronously transfer small HTTP data from the user’s browser to the endpoint we want using a POST request.
Browsers Support:
Chrome : From v37
Firefox (Gecko) : From version 31
Internet Explorer: No supported ( This is really a surprise! )
Opera: From version 24
Safari: Not Supported
Talking about Mobile Browsers, just Firefox Mobile 31.0 supports it.
To use this feature, we will need to pass some extra object to our events this way:
ga('send', 'event', 'Clicks', 'Outgoing', 'Reddit', {useBeacon: true});
When passing this value to our event, Universal Analytics will try to send our hit using this new feature on the browsers that support it, this way our user’s navigation won’t be affected and the event info will be asynchronously sent to Google Analytics even if the user left our page, or even if the user’s closed the browser window. Yep you heard it right, we could even track when user’s close our site’s tab.
Writing navigator.sendBeacon will return undefined if it's not available in our browser
Tracking window.unload will allow us to see how many users close their browser/tab while being in our site. Let’s see how would we do it:
window.addEventListener('unload', trackUnload, false);
function trackUnload() {
ga('send', 'event', 'Unload', location.pathname, {useBeacon: true});
}
Let’s see a piece of pure JavaScript code to learn how this feature really works:
window.addEventListener('unload', trackUnload, false); function logData() { navigator.sendBeacon("/log", JSON.stringify({'unload': location.pathname})); }
This will send a POST request to /log path, with a POST payload inclusing the currentPathName were the user closed our browser window.
I’m sure that there are lot’s of smart people out there that could think in some good use cases for this new feature ( even if it isn’t fully supported by all browser at the moment ). Leave a comment if you have one in your head 🙂