Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(google-tag-manager): refactor, dev option and $gtm.pushEvent #274

Merged
merged 14 commits into from
Apr 15, 2019
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion packages/google-tag-manager/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@ id: () => {
{
id: 'GTM-XXXXXXX',
layer: 'dataLayer',
pageTracking: false
pageTracking: false,
dev: false,
query: {
// query params...
gtm_auth: '...',
Expand All @@ -60,3 +61,12 @@ id: () => {
You can optionally set `pageTracking` option to `true` to track page views.

This is disabled by default to prevent double events when using alongside with Google Analytics so take care before enabling this option.

## Usage

### Pushing events

You can push events into the configured `layer`:
```js
this.$gtm.pushEvent({ event: 'myEvent', ...someAttributes })
```
5 changes: 3 additions & 2 deletions packages/google-tag-manager/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,13 @@ module.exports = async function nuxtTagManager(_options) {
layer: 'dataLayer',
pageTracking: false,
respectDoNotTrack: false,
dev: false,
syffs marked this conversation as resolved.
Show resolved Hide resolved
env: {}, // env is supported for backward compability and is alias of query
query: {}
})

// Don't include when run in dev mode
if (this.options.dev) {
// Don't include when run in dev mode unless dev: true is configured
if (this.options.dev && !options.dev) {
return
}

Expand Down
88 changes: 60 additions & 28 deletions packages/google-tag-manager/plugin.js
Original file line number Diff line number Diff line change
@@ -1,31 +1,63 @@
// Include Google Tag Manager Script
function setup() {
window['<%= options.layer %>'] = window['<%= options.layer %>'] || [];
window['<%= options.layer %>'].push({
event: 'gtm.js', 'gtm.start': new Date().getTime()
});
}

const shouldCheckDNT = <%= options.respectDoNotTrack %>
// Detect Do Not Track settings
const hasDNT = shouldCheckDNT && (window.doNotTrack === '1'
|| navigator.doNotTrack === 'yes'
|| navigator.doNotTrack === '1'
|| navigator.msDoNotTrack === '1'
|| (window.external && window.external.msTrackingProtectionEnabled && window.external.msTrackingProtectionEnabled())
)

if (!hasDNT) setup()

<% if (options.pageTracking) { %>
// Every time the route changes (fired on initialization too)
export default ({ app: { router } }) => {
if (!hasDNT) {
router.afterEach((to, from) => {
setTimeout(() => {
window['<%= options.layer %>'].push(to.gtm || { event: 'nuxtRoute', pageType: 'PageView', pageUrl: to.fullPath, routeName: to.name })
}, 0)
})
// Google Tag Manager Class to be injected
class Gtm {
syffs marked this conversation as resolved.
Show resolved Hide resolved
constructor(ctx, options) {
this.ctx = ctx
this.options = options
}
init() {
window[this.options.layer] = window[this.options.layer] || []

this.pushEvent({
event: 'gtm.js',
'gtm.start': new Date().getTime()
})

if (!this.options.respectDoNotTrack && this.options.pageTracking && !this.hasDNT()) {
this.initPageTracking()
}
}

initPageTracking() {
this.ctx.app.router.afterEach((to, from) => {
setTimeout(() => {
window[this.options.layer].push(to.gtm || { event: 'nuxtRoute', pageType: 'PageView', pageUrl: to.fullPath, routeName: to.name })
}, 0)
})
}

pushEvent(obj) {
try {
if (!window || !window[this.options.layer]) {
throw new Error('missing GTM dataLayer')
}
if (typeof obj !== 'object') {
throw new Error('event should be an object')
}
if (!obj.hasOwnProperty('event')) {
throw new Error('missing event property')
}
window[this.options.layer].push(obj)
} catch (err) {
console.error('[ERROR] [GTM]', err)
}
}
<% } %>

hasDNT() {
return window.doNotTrack === '1' ||
navigator.doNotTrack === 'yes' ||
navigator.doNotTrack === '1' ||
navigator.msDoNotTrack === '1' ||
(window.external && window.external.msTrackingProtectionEnabled && window.external.msTrackingProtectionEnabled())
}
}

export default function(ctx, inject) {
const options = <%= JSON.stringify(options) %>

// Create a new Auth instance
const $gtm = new Gtm(ctx, options)
inject('gtm', $gtm)

$gtm.init()
}