Skip to content

Instantly share code, notes, and snippets.

@alastaircoote
Last active August 29, 2015 13:57
Show Gist options
  • Save alastaircoote/9350466 to your computer and use it in GitHub Desktop.
Save alastaircoote/9350466 to your computer and use it in GitHub Desktop.
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.
try
@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.
return
window.addEventListener "offline", @startOfflineTrack, false
document.addEventListener "visibilitychange", @pageVisibilityChanged, false
@doOnlineOfflineCheck()
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 [Date.now()]
# 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] = Date.now()
window.localStorage.setItem "offlineTrack", JSON.stringify(@trackingArray)
endOfflineTrack: =>
@isTracking = false
if @trackInterval then clearInterval @trackInterval
@setTrackingEnd()
window.removeEventListener "online", @endOfflineTrack, false
@sendData()
sendData: =>
if @trackingArray.length == 0 then return
# turn this into a slightly more readable version
mappedResults = @trackingArray.map (t) ->
{
start: new Date(t[0])
end: new Date(t[1])
}
result = @dataSendFunc mappedResults, =>
@trackingArray = []
window.localStorage.removeItem "offlineTrack"
doOnlineOfflineCheck: =>
if navigator.onLine
@sendData()
else
@startOfflineTrack()
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.
@endOfflineTrack()
else if !navigator.onLine
@startOfflineTrack()
else if !document.hidden && navigator.onLine
# We're back in the foreground and online - send data.
@sendData()
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.
cb()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment