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'] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Conditionally Load Google Analytics
Export
GA
asclass
Plugin
Component
Store
Config