-
Notifications
You must be signed in to change notification settings - Fork 71
/
Copy pathplugin.js
93 lines (84 loc) · 2.44 KB
/
plugin.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import { log } from './gtm.utils'
const _layer = '<%= options.layer %>'
const _id = '<%= options.id %>'
function gtmClient(ctx, initialized) {
return {
init(id = _id) {
if (initialized[id] || !window._gtm_inject) {
return
}
window._gtm_inject(id)
initialized[id] = true
log('init', id)
},
push(obj) {
if (!window[_layer]) {
window[_layer] = []
}
window[_layer].push(obj)
log('push', obj)
}
}
}
function gtmServer(ctx, initialized) {
const events = []
const inits = []
ctx.beforeNuxtRender(() => {
if (!inits.length && !events.length) {
return
}
const gtmScript = ctx.app.head.script.find(s => s.hid == '<%= options.scriptId %>')
gtmScript.innerHTML = `window['${_layer}']=${JSON.stringify(events)};${gtmScript.innerHTML}`
if (inits.length) {
gtmScript.innerHTML += `;${JSON.stringify(inits)}.forEach(function(i){window._gtm_inject(i)})`
}
<% if (options.noscript) { %>
const gtmIframe = ctx.app.head.noscript.find(s => s.hid == '<%= options.noscriptId %>')
const renderIframe = id => `<%= options.renderIframe('${id}') %>`
if (inits.length) {
gtmIframe.innerHTML += inits.map(renderIframe)
}
<% } %>
})
return {
init(id = _id) {
if (initialized[id]) {
return
}
inits.push(id)
initialized[id] = true
log('init', id)
},
push(obj) {
events.push(obj)
log('push', JSON.stringify(obj))
}
}
}
function startPageTracking(ctx) {
ctx.app.router.afterEach((to) => {
setTimeout(() => {
ctx.$gtm.push(to.gtm || {
routeName: to.name,
pageType: 'PageView',
pageUrl: '<%= options.routerBase %>' + to.fullPath,
pageTitle: (typeof document !== 'undefined' && document.title) || '',
event: '<%= options.pageViewEventName %>'
})
}, 250)
})
}
export default function (ctx, inject) {
const runtimeConfig = (ctx.$config && ctx.$config.gtm) || {}
const autoInit = <%= options.autoInit %>
const id = '<%= options.id %>'
const runtimeId = runtimeConfig.id
const initialized = autoInit && id ? {[id]: true} : {}
const $gtm = process.client ? gtmClient(ctx, initialized) : gtmServer(ctx, initialized)
if (autoInit && runtimeId && runtimeId !== id) {
$gtm.init(runtimeId)
}
ctx.$gtm = $gtm
inject('gtm', ctx.$gtm)
<% if (options.pageTracking) { %>if (process.client) { startPageTracking(ctx); }<% } %>
}