Skip to content

Commit 1194b34

Browse files
authored
Use <number>.<number> format for Google Analytics client ID
With the `ENFORCE_RECOMMENDATIONS` [validation behavior](https://developers.google.com/analytics/devguides/collection/protocol/ga4/validating-events?client_type=firebase#send_events_for_validation), Google Analytics warns about client IDs not in the <number>.<number> format. This is not an issue in practice - that recommendation is for compatibility with existing client IDs and events are still processed with a client ID in any format. Additionally, the validation is not enabled by default. However, this PR updates our sample code to use a consistent ID regardless to reduce noise if the validation is enabled. We use a random ID concatenated with a UNIX timestamp to match other GA client libraries.
1 parent bce4254 commit 1194b34

File tree

1 file changed

+15
-2
lines changed

1 file changed

+15
-2
lines changed

functional-samples/tutorial.google-analytics/scripts/google-analytics.js

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,14 +14,27 @@ class Analytics {
1414
this.debug = debug;
1515
}
1616

17+
getRandomId() {
18+
const digits = "123456789".split("");
19+
let result = "";
20+
21+
for (let i = 0; i < 10; i++) {
22+
result += digits[Math.floor(Math.random() * 9)]
23+
}
24+
25+
return result;
26+
}
27+
1728
// Returns the client id, or creates a new one if one doesn't exist.
1829
// Stores client id in local storage to keep the same client id as long as
1930
// the extension is installed.
2031
async getOrCreateClientId() {
2132
let { clientId } = await chrome.storage.local.get('clientId');
2233
if (!clientId) {
23-
// Generate a unique client ID, the actual value is not relevant
24-
clientId = self.crypto.randomUUID();
34+
// Generate a unique client ID, the actual value is not relevant. We use
35+
// the <number>.<number> format since this is typical for GA client IDs.
36+
const unixTimestampSeconds = Math.floor(new Date().getTime() / 1000);
37+
clientId = `${this.getRandomId()}.${unixTimestampSeconds}`;
2538
await chrome.storage.local.set({ clientId });
2639
}
2740
return clientId;

0 commit comments

Comments
 (0)