mirror of
https://github.com/GoogleChrome/chrome-extensions-samples.git
synced 2026-03-26 13:19:49 +07:00
Use <number>.<number> format for Google Analytics client ID (#1606)
* 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. * Run eslint
This commit is contained in:
@@ -14,14 +14,27 @@ class Analytics {
|
||||
this.debug = debug;
|
||||
}
|
||||
|
||||
getRandomId() {
|
||||
const digits = '123456789'.split('');
|
||||
let result = '';
|
||||
|
||||
for (let i = 0; i < 10; i++) {
|
||||
result += digits[Math.floor(Math.random() * 9)];
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// Returns the client id, or creates a new one if one doesn't exist.
|
||||
// Stores client id in local storage to keep the same client id as long as
|
||||
// the extension is installed.
|
||||
async getOrCreateClientId() {
|
||||
let { clientId } = await chrome.storage.local.get('clientId');
|
||||
if (!clientId) {
|
||||
// Generate a unique client ID, the actual value is not relevant
|
||||
clientId = self.crypto.randomUUID();
|
||||
// Generate a unique client ID, the actual value is not relevant. We use
|
||||
// the <number>.<number> format since this is typical for GA client IDs.
|
||||
const unixTimestampSeconds = Math.floor(new Date().getTime() / 1000);
|
||||
clientId = `${this.getRandomId()}.${unixTimestampSeconds}`;
|
||||
await chrome.storage.local.set({ clientId });
|
||||
}
|
||||
return clientId;
|
||||
|
||||
Reference in New Issue
Block a user