Last active
June 25, 2019 17:40
-
-
Save daliborgogic/7bf25f3abb89e38e5b20b2da755a5e56 to your computer and use it in GitHub Desktop.
Google Analytics for Nuxt.js 678bytes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default ({ app }) => { | |
if (process.env.NODE_ENV !== 'production') return | |
const KEY = 'ga:user' | |
const UID = (localStorage[KEY] = localStorage[KEY] || Math.random() + '.' + Math.random()) | |
function encode(obj) { | |
let k | |
let str = 'https://www.google-analytics.com/collect?v=1' | |
for (k in obj) { | |
if (obj[k]) { | |
str += `&${k}=${encodeURIComponent(obj[k])}` | |
} | |
} | |
return str | |
} | |
class GA { | |
constructor(ua, opts = {}) { | |
this.args = Object.assign({ tid: ua, cid: UID }, opts) | |
this.send('pageview') | |
} | |
send(type, opts) { | |
if (type === 'pageview' && !opts) { | |
opts = { dl: location.href, dt: document.title } | |
} | |
let obj = Object.assign({ t: type }, this.args, opts, { z: Date.now() }) | |
new Image().src = encode(obj) | |
} | |
} | |
app.router.onReady(() => { | |
const ga = new GA(process.env.TRACKER_ID) | |
app.router.afterEach(to => ga.send('pageview', { dp: to.fullPath })) | |
}) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default { | |
plugins: ['~/plugins/ga.client.js'] | |
} |
Conditionally Load Google Analytics
Export GA
as class
Plugin
// /plugins/ga.client.js
function encode(obj) {
let k
let str = 'https://www.google-analytics.com/collect?v=1'
for (k in obj) {
if (obj[k]) {
str += `&${k}=${encodeURIComponent(obj[k])}`
}
}
return str
}
export class GA {
constructor(ua, opts = {}) {
const KEY = 'ga:user'
const UID = (localStorage[KEY] = localStorage[KEY] || Math.random() + '.' + Math.random())
this.args = Object.assign({ tid: ua, cid: UID }, opts)
this.send('pageview')
}
send(type, opts) {
if (type === 'pageview' && !opts) {
opts = {
dl: location.href,
dt: document.title,
aip: 0
}
}
let obj = Object.assign({ t: type }, this.args, opts, { z: Date.now() })
new Image().src = encode(obj)
}
}
export default async function ({ store, app: { router } }) {
if (process.env.NODE_ENV !== 'production') return
if (store.state.accepted !== true) return
router.onReady(() => {
const ga = new GA(process.env.UA)
router.afterEach(to => ga.send('pageview', { dp: to.fullPath }))
})
}
Component
<template>
<button @click="accepted">OK</button>
</template>
<script>
import { GA } from '@/plugins/ga.client'
export default {
methods: {
accepted () {
this.$store.commit('setAccepted', true)
document.cookie = 'accepted=true'
new GA(process.env.UA)
}
}
}
</script>
Store
// /store/index.js
const cookieparser = process.server
? require('cookieparser')
: undefined
const state = () => ({
accepted: null
})
const mutations = {
setAccepted: (state, payload) => state.accepted = payload
}
const actions = {
nuxtServerInit({ commit }, { req }) {
let accepted = null
if (req.headers.cookie) {
const parsed = cookieparser.parse(req.headers.cookie)
try {
accepted = JSON.parse(parsed.accepted)
} catch {
// No valid cookie found
}
}
commit('setAccepted', accepted)
}
}
export default {
state,
mutations,
actions
}
Config
// /nuxt.config.js
export default {
plugins: [ '~/plugins/ga.client.js' ]
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
API
GA(trackerID, options)
trackerID
Type:
String
Your Google Analytics tracker ID; eg
UA-XXXXXXXX-X
options.aip
Type:
Integer
Default:
0
Anonymize the sender's IP address. See Anonymize IP.
options.an
Type:
String
Specifies the application's name. See Application Name.
options.aid
Type:
String
Specifies the application identifier. See Application ID.
options.aiid
Type:
String
Specifies the application installer identifier. See Application Installer ID.
options.av
Type:
String
Specifies the application verison. See Application Version.
options.ds
Type:
String
Indicates the data source type of the hit; eg
web
orapp
. See Data Source.ga.send(type, params)
type
Type:
String
The type of hit to send. Must be one of these:
pageview
,screenview
,event
,transaction
,item
,social
,exception
, ortiming
.params
Type:
Object
The parameters to send based on the
type
of hit.Please follow the links for each available parameter set:
For
pageview
hits only, if noparams
are provided, then thedocument.title
andlocation.href
values will be auto-filled. This allows you to send valid requests by writing: