I have a chrome extension and I want to track analytics.
Sending an event is fine, but, remembering users doesn’t seem to be working.
Google is showing every user as new; therefore, when I look at retention, there is no user retention at all.
I’m using this as per the documentation and everything seems to be working when I console log the client ID and session IDs.
Is it a setting in Google Analytics that I’m missing?
I’m building the chrome extension using ReactJS.
import { API } from '../../data/GAnalytics';
export const fetchClientId = async () => {
if (chrome && chrome.storage) {
console.log("chrome.storage is available");
const result = await chrome.storage.local.get('clientId');
let clientId = result.clientId;
if (!clientId) {
clientId = window.crypto.getRandomValues(new Uint32Array(1)).join();
console.log("Generating new clientId:", clientId);
await chrome.storage.local.set({ clientId });
}
return clientId;
} else {
console.error("chrome.storage.local is not available in this context.");
}
}
export const fetchSessionId = async () => {
if (chrome && chrome.storage) {
const result = await chrome.storage.local.get('sessionId');
let sessionId = result.sessionId;
if (!sessionId) {
sessionId = window.crypto.getRandomValues(new Uint32Array(1)).join();
await chrome.storage.local.set({ sessionId });
}
return sessionId;
}
}
export const sendEvent = async (eventName, params) => {
const clientId = await fetchClientId();
console.log('Client ID:', clientId);
const sessionId = await fetchSessionId();
console.log('Session ID:', sessionId);
const GA_ENDPOINT = 'https://www.google-analytics.com/mp/collect';
const MEASUREMENT_ID = API.measurement_id;
const API_SECRET = API.api_secret;
fetch(
`${GA_ENDPOINT}?measurement_id=${MEASUREMENT_ID}&api_secret=${API_SECRET}`,
{
method: 'POST',
body: JSON.stringify({
client_id: clientId,
events: [
{
name: eventName,
params: {
session_id: sessionId,
...params,
},
},
],
}),
}
);
}
export const sendPageView = async () => {
const clientId = await fetchClientId();
const GA_ENDPOINT = 'https://www.google-analytics.com/mp/collect';
const MEASUREMENT_ID = API.measurement_id;
const API_SECRET = API.api_secret;
const DEFAULT_ENGAGEMENT_TIME_IN_MSEC = 10 * 1000;
fetch(
`${GA_ENDPOINT}?measurement_id=${MEASUREMENT_ID}&api_secret=${API_SECRET}`,
{
method: 'POST',
body: JSON.stringify({
client_id: clientId,
events: [
{
name: 'page_view',
params: {
session_id: await fetchSessionId(),
engagement_time_msec: DEFAULT_ENGAGEMENT_TIME_IN_MSEC,
page_title: document.title,
page_location: document.location.href,
},
},
],
}),
}
);
}
{
"manifest_version": 3,
"name": "xxxx",
"version": "xxx",
"description": "xxx",
"permissions": [
"history",
"storage",
"topSites" ],
"short_name": "React Extension",
"icons": {
"16": "/images/icon16.png",
"32": "/images/icon48.png",
"48": "/images/icon48.png",
"128": "/images/icon128.png"
},
"chrome_url_overrides": {
"newtab": "popup.html"
}
}