我正在尝试为Nuxt构建一个Google Analytics(分析)插件,该插件将从CMS中获取跟踪ID。我想我真的很亲近。
我仅在客户端加载插件文件。该插件是通过nuxt.config.js
数组从plugins:[{ src: '~/plugins/google-gtag.js', mode: 'client' }]
加载的。
从那里开始,主要问题是gtag脚本需要在URL中使用UA代码,因此我不能仅仅将其添加到nuxt.config.js
中的常规脚本对象中。我需要从商店中获取那些UA代码(水合形式为nuxtServerInit
。
所以我在插件中使用head.script.push
在URL中添加带有UA代码的gtag脚本。但这并不会导致在第一次页面加载时添加脚本,但是会在所有后续页面转换中添加脚本。所以很明显我在页面渲染中运行head.script.push
太晚了。
但是我不知道如何获取跟踪ID,然后将脚本添加到头部。
// plugins/google.gtag.client.js with "mode": "client
export default ({ store, app: { head, router, context } }, inject) => {
// Remove any empty tracking codes
const codes = store.state.siteMeta.gaTrackingCodes.filter(Boolean)
// Add script tag to head
head.script.push({
src: `https://www.googletagmanager.com/gtag/js?id=${codes[0]}`,
async: true
})
console.log('added script')
// Include Google gtag code and inject it (so this.$gtag works in pages/components)
window.dataLayer = window.dataLayer || []
function gtag() {
dataLayer.push(arguments)
}
inject('gtag', gtag)
gtag('js', new Date())
// Add tracking codes from Vuex store
codes.forEach(code => {
gtag('config', code, {
send_page_view: false // necessary to avoid duplicated page track on first page load
})
console.log('installed code', code)
// After each router transition, log page event to Google for each code
router.afterEach(to => {
gtag('config', code, { page_path: to.fullPath })
console.log('afterEach', code)
})
})
}
我最终使它起作用,我们在production here中使用了它。
撰写本文时的代码如下:
export default ({ store, app: { router, context } }, inject) => {
// Remove any empty tracking codes
let codes = _get(store, "state.siteMeta.gaTrackingCodes", [])
codes = codes.filter(Boolean)
// Abort if no codes
if (!codes.length) {
if (context.isDev) console.log("No Google Anlaytics tracking codes set")
inject("gtag", () => {})
return
}
// Abort if in Dev mode, but inject dummy functions so $gtag events don't throw errors
if (context.isDev) {
console.log("No Google Anlaytics tracking becuase your are in Dev mode")
inject("gtag", () => {})
return
}
// Abort if we already added script to head
let gtagScript = document.getElementById("gtag")
if (gtagScript) {
return
}
// Add script tag to head
let script = document.createElement("script")
script.async = true
script.id = "gtag"
script.src = "//www.googletagmanager.com/gtag/js"
document.head.appendChild(script)
// Include Google gtag code and inject it (so this.$gtag works in pages/components)
window.dataLayer = window.dataLayer || []
function gtag() {
dataLayer.push(arguments)
}
inject("gtag", gtag)
gtag("js", new Date())
// Add tracking codes from Vuex store
codes.forEach(code => {
gtag("config", code, {
send_page_view: false // Necessary to avoid duplicated page track on first page load
})
// After each router transition, log page event to Google for each code
router.afterEach(to => {
gtag("config", code, { page_path: to.fullPath })
})
})
}
如果没有在插件中,那么这是有关如何加载第三方脚本的很好的阅读:https://vueschool.io/articles/vuejs-tutorials/how-to-load-third-party-scripts-in-nuxt-js/