diff --git a/packages/docusaurus-plugin-google-analytics/src/analytics.ts b/packages/docusaurus-plugin-google-analytics/src/analytics.ts index ebf87f036041..82e957701c3a 100644 --- a/packages/docusaurus-plugin-google-analytics/src/analytics.ts +++ b/packages/docusaurus-plugin-google-analytics/src/analytics.ts @@ -5,21 +5,19 @@ * LICENSE file in the root directory of this source tree. */ -import ExecutionEnvironment from '@docusaurus/ExecutionEnvironment'; +import type {ClientModule} from '@docusaurus/types'; -export default (function analyticsModule() { - if (!ExecutionEnvironment.canUseDOM) { - return null; - } - - return { - onRouteDidUpdate({location}: {location: Location}) { +const clientModule: ClientModule = { + onRouteDidUpdate({location, previousLocation}) { + if (previousLocation && location.pathname !== previousLocation.pathname) { // Set page so that subsequent hits on this page are attributed // to this page. This is recommended for Single-page Applications. window.ga('set', 'page', location.pathname); // Always refer to the variable on window in-case it gets // overridden elsewhere. window.ga('send', 'pageview'); - }, - }; -})(); + } + }, +}; + +export default clientModule; diff --git a/packages/docusaurus-plugin-google-gtag/src/gtag.ts b/packages/docusaurus-plugin-google-gtag/src/gtag.ts index e5d782bf3145..0beaac7f0a07 100644 --- a/packages/docusaurus-plugin-google-gtag/src/gtag.ts +++ b/packages/docusaurus-plugin-google-gtag/src/gtag.ts @@ -5,20 +5,16 @@ * LICENSE file in the root directory of this source tree. */ -import ExecutionEnvironment from '@docusaurus/ExecutionEnvironment'; import globalData from '@generated/globalData'; import type {PluginOptions} from '@docusaurus/plugin-google-gtag'; +import type {ClientModule} from '@docusaurus/types'; -export default (function gtagModule() { - if (!ExecutionEnvironment.canUseDOM) { - return null; - } +const {trackingID} = globalData['docusaurus-plugin-google-gtag']! + .default as PluginOptions; - const {trackingID} = globalData['docusaurus-plugin-google-gtag']! - .default as PluginOptions; - - return { - onRouteDidUpdate({location}: {location: Location}) { +const clientModule: ClientModule = { + onRouteDidUpdate({location, previousLocation}) { + if (previousLocation && location.pathname !== previousLocation.pathname) { // Always refer to the variable on window in case it gets overridden // elsewhere. window.gtag('config', trackingID, { @@ -27,9 +23,11 @@ export default (function gtagModule() { }); window.gtag('event', 'page_view', { page_title: document.title, - page_location: location.href, + page_location: window.location.href, page_path: location.pathname, }); - }, - }; -})(); + } + }, +}; + +export default clientModule;