Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Example code for tracking offline usage
class OfflineTrack
constructor: (@dataSendFunc) ->
# dataSendFunc is a function passed in to OfflineTrack to actually store
# this offline tracking data remotely - basically, I wanted to abstract this
# out so that anyone can use whatever tracking system they wish.
@trackingArray = JSON.parse(window.localStorage.getItem("offlineTrack")) || []
catch e
# localStorage doesn't work in incognito mode. If we can't use it,
# we won't track this.
window.addEventListener "offline", @startOfflineTrack, false
document.addEventListener "visibilitychange", @pageVisibilityChanged, false
startOfflineTrack: =>
if @isTracking then return
@isTracking = true
# Check to make sure that the last tracking event has been closed off correctly
lastTrack = @trackingArray[@trackingArray.length - 1]
if lastTrack?.length < 2
# The tracking was never stopped - so we have to disregard.
@trackingArray.splice(@trackingArray.length - 1,1)
@trackingArray.push []
# Update the tracking end every 30 secs
@trackInterval = setInterval @setTrackingEnd, 30000
# When we get back online, stop tracking
window.addEventListener "online", @endOfflineTrack, false
setTrackingEnd: =>
currentTrack = @trackingArray[@trackingArray.length - 1]
currentTrack[1] =
window.localStorage.setItem "offlineTrack", JSON.stringify(@trackingArray)
endOfflineTrack: =>
@isTracking = false
if @trackInterval then clearInterval @trackInterval
window.removeEventListener "online", @endOfflineTrack, false
sendData: =>
if @trackingArray.length == 0 then return
# turn this into a slightly more readable version
mappedResults = (t) ->
start: new Date(t[0])
end: new Date(t[1])
result = @dataSendFunc mappedResults, =>
@trackingArray = []
window.localStorage.removeItem "offlineTrack"
doOnlineOfflineCheck: =>
if navigator.onLine
pageVisibilityChanged: =>
# This is fired when the tab is either hidden or shown. This
# lets us track when someone returns to this page when offline.
if document.hidden && !navigator.onLine
# If we're already tracking offline usage, stop it now.
else if !navigator.onLine
else if !document.hidden && navigator.onLine
# We're back in the foreground and online - send data.
new OfflineTrack (data, cb) ->
# Replace this with your own tracking.
console.log data
# Call the callback to confirm that we've saved our data correctly.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.