Skip to content

Commit

Permalink
feat: ssr iframe injection
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Feb 23, 2020
1 parent da0ae44 commit d678f16
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
8 changes: 6 additions & 2 deletions lib/module.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,12 +84,13 @@ module.exports = async function gtmModule (_options) {
})

// Prepend google tag manager <noscript> fallback to <body>
const renderIframe = id => `<iframe src="${options.noscriptURL + '?id=' + id + '&' + queryString}" height="0" width="0" style="display:none;visibility:hidden" title="gtm"></iframe>`
if (options.noscript && options.id) {
this.options.head.noscript = this.options.head.noscript || []
this.options.head.noscript.push({
hid: options.noscriptId,
pbody: true,
innerHTML: `<iframe src="${options.noscriptURL + '?id=' + options.id + '&' + queryString}" height="0" width="0" style="display:none;visibility:hidden" title="gtm"></iframe>`
innerHTML: options.id ? renderIframe(options.id) : '' /* placeholder for SSR calls */
})
}

Expand All @@ -102,7 +103,10 @@ module.exports = async function gtmModule (_options) {
this.addPlugin({
src: path.resolve(__dirname, 'plugin.js'),
fileName: 'gtm.js',
options
options: {
...options,
renderIframe
}
})
}

Expand Down
8 changes: 8 additions & 0 deletions lib/plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,18 @@ function gtmServer(ctx, initialized) {
if (!inits.length && !events.length) {
return
}

const gtmScript = ctx.app.head.script.find(s => s.hid = '<%= options.scriptId %>')
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)
}
<% } %>
if (events.length) {
gtmScript.innerHTML += `;${JSON.stringify(events)}.forEach(function(e){window['${_layer}'].push(e)})`
}
Expand Down

0 comments on commit d678f16

Please sign in to comment.