From 8779b22190c6f1203b7ce510e1b849f981554fdd Mon Sep 17 00:00:00 2001 From: Julien Boudry Date: Sun, 25 Dec 2022 22:27:38 +0100 Subject: [PATCH] New Google Analytics 4 plugin --- build/build.js | 1 + docs/plugins.md | 24 +++++++++++++++++++++++- src/plugins/ga4.js | 44 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 68 insertions(+), 1 deletion(-) create mode 100644 src/plugins/ga4.js diff --git a/build/build.js b/build/build.js index 0de786828..53e8d1133 100644 --- a/build/build.js +++ b/build/build.js @@ -80,6 +80,7 @@ async function buildAllPlugin() { var plugins = [ {name: 'search', input: 'search/index.js'}, {name: 'ga', input: 'ga.js'}, + {name: 'ga4', input: 'ga4.js'}, {name: 'matomo', input: 'matomo.js'}, {name: 'emoji', input: 'emoji.js'}, {name: 'external-script', input: 'external-script.js'}, diff --git a/docs/plugins.md b/docs/plugins.md index 3db7ff56b..0b4aff7fb 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -69,7 +69,7 @@ This plugin ignores diacritical marks when performing a full text search (e.g., ``` -## Google Analytics +## Google Universal Analytics (GA3) Install the plugin and configure the track id. @@ -91,6 +91,28 @@ Configure by `data-ga`. ``` +## Google Analytics 4 (GA4) + +Install the plugin and configure the gtag id. + +```html + + + +``` + +Configure by `data-gtag`. + + +```html + + +``` + ## Emoji Renders a larger collection of emoji shorthand codes. Without this plugin, Docsify is able to render only a limited number of emoji shorthand codes. diff --git a/src/plugins/ga4.js b/src/plugins/ga4.js new file mode 100644 index 000000000..de0ccd2cd --- /dev/null +++ b/src/plugins/ga4.js @@ -0,0 +1,44 @@ +/* eslint-disable no-console */ +// Inspired by https://github.com/egoist/vue-ga/blob/master/src/index.js +function appendScript(id) { + const script = document.createElement('script'); + script.async = true; + script.src = 'https://www.googletagmanager.com/gtag/js?id='+id; + document.body.appendChild(script); + } + + function init(id) { + appendScript(id); + + window.dataLayer = window.dataLayer || []; + + gtag = function() {dataLayer.push(arguments)}; + gtag('js', new Date()); + + gtag('config', id, { + send_page_view: false, // Disable automatic pageview + debug_mode: (location.hostname === 'localhost') ? true : false + }); + } + + function collect() { + if (typeof gtag === 'undefined') { + init($docsify.gtag); + } + + gtag('event', 'page_view', { + page_title: location.hash, + page_location: location.href + }); + } + + const install = function (hook) { + if (!$docsify.gtag) { + console.error('[Docsify] gtag is required.'); + return; + } + + hook.beforeEach(collect); + }; + + $docsify.plugins = [].concat(install, $docsify.plugins);