Skip to content
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

fix(gtag): send the newly rendered page's title instead of the old one's #7424

Merged
merged 5 commits into from
May 27, 2022
Merged
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
27 changes: 17 additions & 10 deletions packages/docusaurus-plugin-google-gtag/src/gtag.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,23 @@ const {trackingID} = globalData['docusaurus-plugin-google-gtag']!
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, {
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,
// 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
// execution to the next tick.
// See: https://github.com/facebook/docusaurus/issues/7420
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,
});
});
}
},
Expand Down
14 changes: 10 additions & 4 deletions website/_dogfooding/clientModuleExample.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,16 @@ function logPage(
location: Location,
previousLocation: Location | null,
): void {
console.log(`${event}
Previous location: ${previousLocation?.pathname}
Current location: ${location.pathname}
Current heading: ${document.getElementsByTagName('h1')[0]?.innerText}`);
console.log(event, location.pathname, {
location,
prevLocation: previousLocation,
heading: document.getElementsByTagName('h1')[0]?.innerText,
title: document.title,
description: (
document.querySelector('meta[name="description"]') as HTMLMetaElement
)?.content,
htmlClassName: document.getElementsByTagName('html')[0]?.className,
});
}

export function onRouteUpdate({
Expand Down