From 4d5e39abffb9156be0a57b5eea228d80e5531f72 Mon Sep 17 00:00:00 2001 From: Erin Noe-Payne Date: Mon, 6 Dec 2021 10:34:19 -0500 Subject: [PATCH] Analytics: Add user id tracking to google analytics (#42763) --- package.json | 1 + .../echo/backends/analytics/GABackend.ts | 17 ++++++++++++----- yarn.lock | 8 ++++++++ 3 files changed, 21 insertions(+), 5 deletions(-) diff --git a/package.json b/package.json index 88152f7b658..4a204f9aa81 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/public/app/core/services/echo/backends/analytics/GABackend.ts b/public/app/core/services/echo/backends/analytics/GABackend.ts index 422e9b2d9f9..6a6401f73e3 100644 --- a/public/app/core/services/echo/backends/analytics/GABackend.ts +++ b/public/app/core/services/echo/backends/analytics/GABackend.ts @@ -8,6 +8,7 @@ export interface GAEchoBackendOptions { export class GAEchoBackend implements EchoBackend { 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 { - 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 diff --git a/yarn.lock b/yarn.lock index 769556400db..b52861d7045 100644 --- a/yarn.lock +++ b/yarn.lock @@ -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