Analytics: Add user id tracking to google analytics (#42763)

This commit is contained in:
Erin Noe-Payne 2021-12-06 10:34:19 -05:00 committed by GitHub
parent 8318fab960
commit 4d5e39abff
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 21 additions and 5 deletions

View File

@ -107,6 +107,7 @@
"@types/enzyme": "3.10.5",
"@types/enzyme-adapter-react-16": "1.0.6",
"@types/file-saver": "2.0.1",
"@types/google.analytics": "^0.0.42",
"@types/grafana__slate-react": "npm:@types/slate-react@0.22.5",
"@types/history": "^4.7.8",
"@types/hoist-non-react-statics": "3.3.1",

View File

@ -8,6 +8,7 @@ export interface GAEchoBackendOptions {
export class GAEchoBackend implements EchoBackend<PageviewEchoEvent, GAEchoBackendOptions> {
supportedEvents = [EchoEventType.Pageview];
trackedUserId: number | null = null;
constructor(public options: GAEchoBackendOptions) {
const url = `https://www.google-analytics.com/analytics${options.debug ? '_debug' : ''}.js`;
@ -18,8 +19,8 @@ export class GAEchoBackend implements EchoBackend<PageviewEchoEvent, GAEchoBacke
cache: true,
});
const ga = ((window as any).ga =
(window as any).ga ||
const ga = (window.ga =
window.ga ||
// this had the equivalent of `eslint-disable-next-line prefer-arrow/prefer-arrow-functions`
function () {
(ga.q = ga.q || []).push(arguments);
@ -30,12 +31,18 @@ export class GAEchoBackend implements EchoBackend<PageviewEchoEvent, GAEchoBacke
}
addEvent = (e: PageviewEchoEvent) => {
if (!(window as any).ga) {
if (!window.ga) {
return;
}
(window as any).ga('set', { page: e.payload.page });
(window as any).ga('send', 'pageview');
window.ga('set', { page: e.payload.page });
window.ga('send', 'pageview');
const { userSignedIn, userId } = e.meta;
if (userSignedIn && userId !== this.trackedUserId) {
this.trackedUserId = userId;
window.ga('set', 'userId', userId);
}
};
// Not using Echo buffering, addEvent above sends events to GA as soon as they appear

View File

@ -9015,6 +9015,13 @@ __metadata:
languageName: node
linkType: hard
"@types/google.analytics@npm:^0.0.42":
version: 0.0.42
resolution: "@types/google.analytics@npm:0.0.42"
checksum: c64b3f7991c4bcb1dfe8db902a2e2ebe821ce53a1ca36e6628b4d08d0c24213aa0d4f49492b3144dd6bfa661f53fb1ecf16e83cca522cddd6d9f8419a4b73fe8
languageName: node
linkType: hard
"@types/graceful-fs@npm:^4.1.2":
version: 4.1.5
resolution: "@types/graceful-fs@npm:4.1.5"
@ -19263,6 +19270,7 @@ __metadata:
"@types/enzyme": 3.10.5
"@types/enzyme-adapter-react-16": 1.0.6
"@types/file-saver": 2.0.1
"@types/google.analytics": ^0.0.42
"@types/grafana__slate-react": "npm:@types/slate-react@0.22.5"
"@types/history": ^4.7.8
"@types/hoist-non-react-statics": 3.3.1