Skip to content

Commit

Permalink
feat(analytics): allow query/hash changes to be sent to GA (#7545)
Browse files Browse the repository at this point in the history
Co-authored-by: Lane Goolsby <lanegoolsby@rocketmortgage.com>
  • Loading branch information
lanegoolsby and Lane Goolsby committed Jun 2, 2022
1 parent f25ee0c commit 1efcfc4
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 13 deletions.
13 changes: 11 additions & 2 deletions packages/docusaurus-plugin-google-analytics/src/analytics.ts
Expand Up @@ -9,10 +9,19 @@ import type {ClientModule} from '@docusaurus/types';

const clientModule: ClientModule = {
onRouteDidUpdate({location, previousLocation}) {
if (previousLocation && location.pathname !== previousLocation.pathname) {
if (
previousLocation &&
(location.pathname !== previousLocation.pathname ||
location.search !== previousLocation.search ||
location.hash !== previousLocation.hash)
) {
// 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);
window.ga(
'set',
'page',
location.pathname + location.search + location.hash,
);
// Always refer to the variable on window in-case it gets
// overridden elsewhere.
window.ga('send', 'pageview');
Expand Down
18 changes: 7 additions & 11 deletions packages/docusaurus-plugin-google-gtag/src/gtag.ts
Expand Up @@ -5,16 +5,16 @@
* LICENSE file in the root directory of this source tree.
*/

import globalData from '@generated/globalData';
import type {PluginOptions} from './options';
import type {ClientModule} from '@docusaurus/types';

const {trackingID} = globalData['docusaurus-plugin-google-gtag']!
.default as PluginOptions;

const clientModule: ClientModule = {
onRouteDidUpdate({location, previousLocation}) {
if (previousLocation && location.pathname !== previousLocation.pathname) {
if (
previousLocation &&
(location.pathname !== previousLocation.pathname ||
location.search !== previousLocation.search ||
location.hash !== previousLocation.hash)
) {
// Normally, the document title is updated in the next tick due to how
// `react-helmet-async` updates it. We want to send the current document's
// title to gtag instead of the old one's, so we use `setTimeout` to defer
Expand All @@ -23,14 +23,10 @@ const clientModule: ClientModule = {
setTimeout(() => {
// Always refer to the variable on window in case it gets overridden
// elsewhere.
window.gtag('config', trackingID, {
page_path: location.pathname,
page_title: document.title,
});
window.gtag('event', 'page_view', {
page_title: document.title,
page_location: window.location.href,
page_path: location.pathname,
page_path: location.pathname + location.search + location.hash,
});
});
}
Expand Down

0 comments on commit 1efcfc4

Please sign in to comment.