UNPKG

2.17 kBJavaScriptView Raw
1const _layer = '<%= options.layer %>'
2const _id = '<%= options.id %>'
3
4function gtmClient(ctx, initialized) {
5 return {
6 init(id = _id) {
7 if (initialized[id] || !window._gtm_inject) {
8 return
9 }
10 window._gtm_inject(id)
11 initialized[id] = true
12 },
13 push(obj) {
14 if (!window[_layer]) {
15 window[_layer] = [{ 'gtm.start': new Date().getTime(), event: 'gtm.js' }]
16 }
17 window[_layer].push(obj)
18 }
19 }
20}
21
22function gtmServer(ctx, initialized) {
23 const events = []
24 const inits = []
25
26 ctx.beforeNuxtRender(() => {
27 if (!inits.length && !events.length) {
28 return
29 }
30
31 const gtmScript = ctx.app.head.script.find(s => s.hid = '<%= options.scriptId %>')
32 if (inits.length) {
33 gtmScript.innerHTML += `;${JSON.stringify(inits)}.forEach(function(i){window._gtm_inject(i)})`
34 }
35<% if (options.noscript) { %>
36 const gtmIframe = ctx.app.head.noscript.find(s => s.hid = '<%= options.noscriptId %>')
37 const renderIframe = id => `<%= options.renderIframe('${id}') %>`
38 if (inits.length) {
39 gtmIframe.innerHTML += inits.map(renderIframe)
40 }
41<% } %>
42 if (events.length) {
43 gtmScript.innerHTML += `;${JSON.stringify(events)}.forEach(function(e){window['${_layer}'].push(e)})`
44 }
45 })
46
47 return {
48 init(id = _id) {
49 if (initialized[id]) {
50 return
51 }
52 inits.push(id)
53 initialized[id] = true
54 },
55 push(obj) {
56 events.push(obj)
57 }
58 }
59}
60
61function startPageTracking(ctx) {
62 ctx.app.router.afterEach((to) => {
63 setTimeout(() => {
64 ctx.$gtm.push(to.gtm || {
65 routeName: to.name,
66 pageType: 'PageView',
67 pageUrl: to.fullPath,
68 pageTitle: (typeof document !== 'undefined' && document.title) || '',
69 event: '<%= options.pageViewEventName %>'
70 })
71 }, 250)
72 })
73}
74
75export default function (ctx, inject) {
76 const initialized = {<%= (options.autoInit && options.id) ? ` '${options.id}': true ` : '' %>}
77 ctx.$gtm = process.client ? gtmClient(ctx, initialized) : gtmServer(ctx, initialized)
78 inject('gtm', ctx.$gtm)
79 <% if (options.pageTracking) { %>if (process.client) { startPageTracking(ctx); }<% } %>
80}