SuspiciousBeaver SuspiciousBeaver - 5 months ago 37
Javascript Question

Can I add Google Analytics to a Chrome extension which doesn't have a popup.html?

My chrome extension is recognising a specific tab's URL, and then, on icon click, it modifies that active tab's content.
I would like to gauge the usage of it, in some way. This is the extension's logic:

- manifest.json [injecting jquery & jquery plugin]
- background.js [ on extension's icon click, it executes content_script.js and tracking.js]
- icon
- content_script.js [ it modifies page content ]
- tracking.js (GA code, as provided by google Analytics then modified according to https://davidsimpson.me/2014/05/27/add-googles-universal-analytics-tracking-chrome-extension/ );





I would like to see how many times extension's button is clicked. I tried adding the appropriate permissions to manifest.json:

"content_security_policy": "script-src 'self' https://www.google-analytics.com; object-src 'self'"


and adding Analytics code to a separate .js file (tracking.js), and executing it when the extension's icon is clicked, as specified in background.js below:

chrome.browserAction.onCLicked.addListener(
function(tab) {
chrome.tabs.executeScript(null, {file:
"content_script.js"});
chrome.tabs.executeScript(null, {file:
"tracking.js"});
});


.. it doesn't work, in the sense that Google Analytics is telling me 'tracking not installed', and I cannot think of another way of adding it.

How can I see this extension's usage?

Xan Xan
Answer

What you are trying to do is to inject tracking into a tab as a content script.

Tracking works by adding another <script> tag into the page, which kicks it out of your content script's isolated context and into the page's context. That's why your script can't see the tracking enabled (and you possibly just broke the page's own tracking too).

You need to install the tracking code in your background page and send events from there. To do so, simply include tracking.js to the list of background scripts; after that, send events in the usual GA way.