Log Chrome extension telemetry with Google Analytics
You are probably wondering how your Chrome extension is being used in production and what exceptions are being generated. One of the ways to quickly instrument your extension with telemetry is to use Google Analytics. Especially, If you are already subscribed to other tools in the Google platform.
Adding Google Analytics to Chrome extension manifest
Google Analytics snippet is only for bootstrapping. The actual code is downloaded from Google server at runtime. By default, Chrome extensions do not allow cross site requests, so you will need to update the content security policy (CSP) in the manifest file.
"content_security_policy": "script-src 'self' https://ssl.google-analytics.com; object-src 'self'"
Important: You will need to declare that you are using remote code and its purpose when publishing the extension in Chrome Web Store. So far, I had no problems passing Chrome extension validation due to Google Analytics code.
Initializing Google Analytics
Now that CSP policy is configured you can initialize Google Analytics with your account ID in the background script. Without worrying that cross-origin requests will be blocked.
Example snippet:
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-00000000-0']);
let isAnalyticsInitialised = false;
function loadAnalytics() {
if (isAnalyticsInitialised) {
return;
}
isAnalyticsInitialised = true;
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = 'https://ssl.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
}
loadAnalytics();
Logging extension events
You can start pushing events to _gaq array even before Google Analytics finishes fetching the scripts. Library is made in the way that events will be sent to Google Analytics server once ga.js is done loading.
Logging snippet:
chrome.browserAction.onClicked.addListener(() => {
_gaq.push(['_trackEvent', 'extension', 'open', 'browserAction']);
});
Manifest V3 considerations
Chrome extension manifest v3 forbids remote code execution. This means that Google Analytics code must be packaged together with the extension and cannot be downloaded from the internet.
We will cover this implementation in the future article as manifest v3 becomes a hard requirement for the new extensions.