1 | const _layer = '<%= options.layer %>'
|
2 | const _id = '<%= options.id %>'
|
3 |
|
4 | function 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 |
|
22 | function 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 |
|
61 | function 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 |
|
75 | export 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 | }
|