Skip to content

feat($plugin-google-analytics): ga4(fix #2713) #2820

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions packages/@vuepress/plugin-google-analytics/enhanceAppFileV4.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Patch for Google Analytics 4

/* global GM_ID */
export default (_ctx) => {
// Google analytics integration
if (process.env.NODE_ENV === 'production' && GM_ID && typeof window !== 'undefined') {
(function (global, doc, tag, src, script, m) {
script = doc.createElement(tag)
m = doc.getElementsByTagName(tag)[0]
script.async = 1
script.src = src
m.parentNode.insertBefore(script, m)
global.dataLayer = global.dataLayer || []
if (!global.gtag) {
global.gtag = function gtag () {
global.dataLayer.push(arguments)
}
global.gtag('js', new Date())
global.gtag('config', GM_ID)
}
})(window, document, 'script', `https://www.googletagmanager.com/gtag/js?id=${GM_ID}`)
}
}
10 changes: 8 additions & 2 deletions packages/@vuepress/plugin-google-analytics/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,15 @@ module.exports = (options = {}, context) => ({
define () {
const { siteConfig = {}} = context
const ga = options.ga || siteConfig.ga
const gm = options.gm || siteConfig.gm
const GA_ID = ga || false
return { GA_ID }
// GM_ID is the Google Analytics ID for GA4
const GM_ID = gm || false
return { GA_ID, GM_ID }
},

enhanceAppFiles: path.resolve(__dirname, 'enhanceAppFile.js')
enhanceAppFiles: [
path.resolve(__dirname, 'enhanceAppFile.js'),
path.resolve(__dirname, 'enhanceAppFileV4.js')
]
})