For using google analytics with mv3 the easiest way is to use measurement protocol.
In short, it allows you to send event tracking to Google Analytics through a normal POST call.
Here's the setup I used to track a click / other events:
The user clicks a button in the extension
The content script/popup.html sends a message to the service worker (background.js) using Message Passing saying the event should be recorded.
The service worker posts the event to Google Analytics using fetch()
And here's some sample code that runs in the service worker:
const ANALYTICS_PATH = "https://www.google-analytics.com/collect";
async function postData(url = '', data = {}) {
// Default options are marked with *
const response = await fetch(url, {
method: 'POST',
mode: 'no-cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow',
referrerPolicy: 'no-referrer',
body: data
});
}
var gaParams = new URLSearchParams();
gaParams.append("v", 1);
gaParams.append("tid", "UA-XXXX-X");
gaParams.append("cid", xxxxx);
gaParams.append("t", "event");
gaParams.append("ec", "myEventCategory");
gaParams.append("ea", "myEventAction");
postData(ANALYTICS_PATH, gaParams)
Note:- This api does not give response codes if something is wrong, instead of using https://www.google-analytics.com/mp/collect directly on prod, one should first try https://www.google-analytics.com/debug/mp/collect.
PS. I found this solution from a comment on this source:-
https://www.indiehackers.com/post/how-to-add-google-analytics-with-manifest-v3-468f1750dc