vuejs/vuepress

Support google analytics 4

lz1998 opened this issue ยท 8 comments

Feature request

support google analytics 4

use gtag.js

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=XXXXXXXXX"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'G-xxxxx');
</script>

I applied a new media, and use Google Analytics Plugin, but it doesn't work.

The new ID is like 'G-xxxxx', not 'UA-00000000-0'

In lack of response, i'm using right now this fork.
https://github.com/scopewu/vuepress
I'm waiting for the results.
I'll let you know if that works.

Yes, please fix this. It is not possible to create a UA-XXXXXXX tag anymore.

Yes, please fix this. It is not possible to create a UA-XXXXXXX tag anymore.

Oh didn't notice that. I thought it's still optional to use version 3 or version 4.


As the GA4 is a breaking version, maybe we should create a new plugin called @vuepress/plugin-google-analytics-4 ?

As the GA4 is a breaking version, maybe we should create a new plugin called @vuepress/plugin-google-analytics-4 ?

Go for it ๐Ÿ‘

Is there any new news on this?

It seems that the GA4 support is now in beta and available via @vuepress/plugin-google-analytics@next, the documentation also seems updated. However, I'm having some issues making it work with Vuepress 1.x, not sure why. Perhaps it hasn't been backported yet?

Anyway, just wanted to share a valid workaround for anyone who is not able to use the new version of the package, for whatever reason.

Via the config file and its head array, you can inject additional tags to the page header. It's relatively trivial to add the proposed tracking code to the page, something along the following lines:

module.exports = {
    head: [
        [
            'script',
            {
                async: true,
                src: 'https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX',
            },
        ],
        [
            'script',
            {},
            [
                "window.dataLayer = window.dataLayer || [];\nfunction gtag(){dataLayer.push(arguments);}\ngtag('js', new Date());\ngtag('config', 'G-XXXXXXXXXX');",
            ],
        ],
    ],
};

Just take care to replace the measurement ID in two places, and you'll be good to go.

It has been supported in vuepress v2, which is not compatible with v1.

For v1 users, try the snippets that provided by @dvuckovic

In case anyone still need this, I've written a plugin specifically for google analytics 4 to work under vuepress v1, which is available here: https://github.com/laphets/vuepress-plugin-google-analytics-4.