Skip to content

Commit

Permalink
fix(analytics) - no tracking when on development (#182)
Browse files Browse the repository at this point in the history
  • Loading branch information
vnglst authored Mar 11, 2019
1 parent 5a2b07f commit fc3e934
Show file tree
Hide file tree
Showing 4 changed files with 124 additions and 32 deletions.
21 changes: 0 additions & 21 deletions public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -159,25 +159,4 @@
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>

<script>
(function(a,b,c){var d=a.history,e=document,f=navigator||{},g=localStorage,
h=encodeURIComponent,i=d.pushState,k=function(){return Math.random().toString(36)},
l=function(){return g.cid||(g.cid=k()),g.cid},m=function(r){var s=[];for(var t in r)
r.hasOwnProperty(t)&&void 0!==r[t]&&s.push(h(t)+"="+h(r[t]));return s.join("&")},
n=function(r,s,t,u,v,w,x){var z="https://www.google-analytics.com/collect",
A=m({v:"1",ds:"web",aip:c.anonymizeIp?1:void 0,tid:b,cid:l(),t:r||"pageview",
sd:c.colorDepth&&screen.colorDepth?screen.colorDepth+"-bits":void 0,dr:e.referrer||
void 0,dt:e.title,dl:e.location.origin+e.location.pathname+e.location.search,ul:c.language?
(f.language||"").toLowerCase():void 0,de:c.characterSet?e.characterSet:void 0,
sr:c.screenSize?(a.screen||{}).width+"x"+(a.screen||{}).height:void 0,vp:c.screenSize&&
a.visualViewport?(a.visualViewport||{}).width+"x"+(a.visualViewport||{}).height:void 0,
ec:s||void 0,ea:t||void 0,el:u||void 0,ev:v||void 0,exd:w||void 0,exf:"undefined"!=typeof x&&
!1==!!x?0:void 0});if(f.sendBeacon)f.sendBeacon(z,A);else{var y=new XMLHttpRequest;
y.open("POST",z,!0),y.send(A)}};d.pushState=function(r){return"function"==typeof d.onpushstate&&
d.onpushstate({state:r}),setTimeout(n,c.delay||10),i.apply(d,arguments)},n(),
a.ma={trackEvent:function o(r,s,t,u){return n("event",r,s,t,u)},
trackException:function q(r,s){return n("exception",null,null,null,null,r,s)}}})
(window,"UA-135954444-1",{anonymizeIp:true,colorDepth:true,characterSet:true,screenSize:true,language:true});
</script>
</html>
18 changes: 7 additions & 11 deletions src/index.tsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,18 @@
import bugsnag from '@bugsnag/js'
import bugsnagReact from '@bugsnag/plugin-react'
import { Router } from '@reach/router'
import preventDoubleTapZoom from 'prevent-double-tap-zoom'
import * as React from 'react'
import * as ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import { applyMiddleware, compose, createStore } from 'redux'

import FindingColors from 'src/finding-colors'
import FindingWords from 'src/finding-words'
import { audioMiddleware } from 'src/finding-words/redux/audio-middleware'
import { IStoreState } from 'src/finding-words/types'
import rootReducer from 'src/shared/redux/root-reducer'
import './index.css'
import registerServiceWorker from './registerServiceWorker'

preventDoubleTapZoom({ delay: 500 })
import { initializeAnalytics } from './shared/utils/analytics'
import { BugsnagErrorBoundary } from './shared/utils/bugsnag'

const composeEnhancers =
(window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose
Expand All @@ -25,19 +22,18 @@ const store = createStore<IStoreState, any, any, any>(
composeEnhancers(applyMiddleware(audioMiddleware))
)

const bugsnagClient = bugsnag('eb9c66e47f7f95c5801a21ffe1308619')
bugsnagClient.use(bugsnagReact, React)
const ErrorBoundary = bugsnagClient.getPlugin('react')

ReactDOM.render(
<ErrorBoundary>
<BugsnagErrorBoundary>
<Provider store={store}>
<Router>
<FindingWords path="/" default={true} />
<FindingColors path="/colors" />
</Router>
</Provider>
</ErrorBoundary>,
</BugsnagErrorBoundary>,
document.getElementById('root') as HTMLElement
)

preventDoubleTapZoom({ delay: 500 })
registerServiceWorker()
initializeAnalytics()
110 changes: 110 additions & 0 deletions src/shared/utils/analytics.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
function initialize(context, trackingId, options) {
const history = context.history
const doc = document
const nav = navigator || {}
const storage = localStorage
const encode = encodeURIComponent
const pushState = history.pushState
const typeException = 'exception'
const generateId = () => Math.random().toString(36)
const getId = () => {
if (!storage.cid) {
storage.cid = generateId()
}
return storage.cid
}
const serialize = obj => {
var str = []
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
if (obj[p] !== undefined) {
str.push(encode(p) + '=' + encode(obj[p]))
}
}
}
return str.join('&')
}
const track = (
type,
eventCategory,
eventAction,
eventLabel,
eventValue,
exceptionDescription,
exceptionFatal
) => {
const url = 'https://www.google-analytics.com/collect'
const data = serialize({
v: '1',
ds: 'web',
aip: options.anonymizeIp ? 1 : undefined,
tid: trackingId,
cid: getId(),
t: type || 'pageview',
sd:
options.colorDepth && context.screen.colorDepth
? `${context.screen.colorDepth}-bits`
: undefined,
dr: doc.referrer || undefined,
dt: doc.title,
dl: doc.location.origin + doc.location.pathname + doc.location.search,
ul: options.language ? (nav.language || '').toLowerCase() : undefined,
de: options.characterSet ? doc.characterSet : undefined,
sr: options.screenSize
? `${(context.screen || {}).width}x${(context.screen || {}).height}`
: undefined,
vp:
options.screenSize && context.visualViewport
? `${(context.visualViewport || {}).width}x${
(context.visualViewport || {}).height
}`
: undefined,
ec: eventCategory || undefined,
ea: eventAction || undefined,
el: eventLabel || undefined,
ev: eventValue || undefined,
exd: exceptionDescription || undefined,
exf:
typeof exceptionFatal !== 'undefined' && !!exceptionFatal === false
? 0
: undefined
})

if (nav.sendBeacon) {
nav.sendBeacon(url, data)
} else {
var xhr = new XMLHttpRequest()
xhr.open('POST', url, true)
xhr.send(data)
}
}
const trackEvent = (category, action, label, value) =>
track('event', category, action, label, value)
const trackException = (description, fatal) =>
track(typeException, null, null, null, null, description, fatal)
history.pushState = function(state) {
if (typeof history.onpushstate == 'function') {
history.onpushstate({ state: state })
}
setTimeout(track, options.delay || 10)
return pushState.apply(history, arguments)
}
track()
context.ma = {
trackEvent,
trackException
}
}

export function initializeAnalytics() {
// only track on production
if (process.env.NODE_ENV !== 'production') return

initialize(window, 'UA-135954444-1', {
anonymizeIp: true,
colorDepth: true,
characterSet: true,
screenSize: true,
language: true
})
}
7 changes: 7 additions & 0 deletions src/shared/utils/bugsnag.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import bugsnag from '@bugsnag/js'
import bugsnagReact from '@bugsnag/plugin-react'
import * as React from 'react'

export const bugsnagClient = bugsnag('eb9c66e47f7f95c5801a21ffe1308619')
bugsnagClient.use(bugsnagReact, React)
export const BugsnagErrorBoundary = bugsnagClient.getPlugin('react')

0 comments on commit fc3e934

Please sign in to comment.